二叉排序树或者是一棵空树,或者是具有下列性质的
二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的
根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
(4)没有键值相等的节点。
那么如何执行插入一个节点操作:
首先找出被插结点的父亲结点。
判断被插结点是其父亲结点的左、右儿子。将被插结点作为
叶子结点插入。
void Insert_Number(Node *root,Node *p)
{
if (root == NULL) return;
if (root->data > p->data)
{
if (root->lchild == NULL) root->lchild = p;
else Insert_Number(root->lchild, p);
}
else
{
if (root->rchild == NULL) root->rchild = p;
else
Insert_Number(root->rchild, p);
}
}
若
二叉树为空。则首先单独生成根结点。
注意:新插入的结点总是叶子结点。
前序遍历操作:
void Pre_Tre(Node *root)
{
if (root == NULL) return;
if (flag)
{
flag = false;
printf("%d", root->data);
}
else printf(" %d", root->data);
Pre_Tre(root->lchild);
Pre_Tre(root->rchild);
}
中序遍历操作:
void InOrder_Tre(Node *root)
{
if (root == NULL) return;
//system("PAUSE");
InOrder_Tre(root->lchild);
if (flag)
{
flag = false;
printf("%d", root->data);
}
else printf(" %d", root->data);
InOrder_Tre(root->rchild);
}
后序遍历操作:
void Last_Tre(Node *root)
{
if (root == NULL) return;
//system("PAUSE");
Last_Tre(root->lchild);
Last_Tre(root->rchild);
if (flag)
{
flag = false;
printf("%d", root->data);
}
else printf(" %d", root->data);
}
</pre><pre code_snippet_id="1640001" snippet_file_name="blog_20160409_4_5399893" name="code" class="cpp">
完整的代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
bool flag;
struct Node
{
int data;
struct Node *lchild, *rchild;
};
void Insert_Number(Node *root,Node *p)
{
if (root == NULL) return;
if (root->data > p->data)
{
if (root->lchild == NULL) root->lchild = p;
else Insert_Number(root->lchild, p);
}
else
{
if (root->rchild == NULL) root->rchild = p;
else
Insert_Number(root->rchild, p);
}
}
void Pre_Tre(Node *root)
{
if (root == NULL) return;
if (flag)
{
flag = false;
printf("%d", root->data);
}
else printf(" %d", root->data);
//system("PAUSE");
Pre_Tre(root->lchild);
Pre_Tre(root->rchild);
}
void InOrder_Tre(Node *root)
{
if (root == NULL) return;
//system("PAUSE");
InOrder_Tre(root->lchild);
if (flag)
{
flag = false;
printf("%d", root->data);
}
else printf(" %d", root->data);
InOrder_Tre(root->rchild);
}
void Last_Tre(Node *root)
{
if (root == NULL) return;
//system("PAUSE");
Last_Tre(root->lchild);
Last_Tre(root->rchild);
if (flag)
{
flag = false;
printf("%d", root->data);
}
else printf(" %d", root->data);
}
int main()
{
int testcas;
scanf("%d", &testcas);
int n;
while (testcas--)
{
scanf("%d", &n);
Node *root;
root = new Node();
scanf("%d", &root->data);
root->lchild = root->rchild = NULL;
for (int i = 1; i < n; i++)
{
int cnt;
scanf("%d", &cnt);
Node *p = new Node();
p->data = cnt;
p->lchild = p->rchild = NULL;
Insert_Number(root, p);
}
flag = true;
//printf("%d %d %d\n", root.data, root.lchild->data, root.rchild->data);
Pre_Tre(root);
printf("\n");
flag = true;
InOrder_Tre(root);
printf("\n");
flag = true;
Last_Tre(root);
printf("\n\n");
}
return 0;
}