输入一系列整数,建立二叉排序数,并进行前序,中序,后序遍历。
前序遍历:根->左->右
中序遍历:左->根->右
后序遍历:左->右->根
struct Tree
{
int data;
Tree* Left;
Tree* Right;
};
bool Insert(int data,Tree *&T)
{
if (T == NULL)
{
T = new Tree;
T->data = data;
T->Left = T->Right = NULL;
}
if (T->data == data)
return false;
else {
if (data < T->data)
return Insert(data, T->Left);
else if (data>T->data)
return Insert(data, T->Right);
}
return T;
}
void visit(Tree *t)
{
printf("%d ", t->data);
}
void qx(Tree* t)
{
if (t != NULL)
{
visit(t);
qx(t->Left);
qx(t->Right);
}
}
void zx(Tree* t)
{
if (t != NULL)
{
zx(t->Left);
visit(t);
zx(t->Right);
}
}
void hx(Tree* t)
{
if (t != NULL)
{
hx(t->Left);
hx(t->Right);
visit(t);
}
}
void slove()
{
Tree *tree;
//tree = NULL;
int n,tmp;
while (~scanf("%d",&n))
{
tree = NULL;
for (int i = 0; i < n; ++i)
{
scanf("%d", &tmp);
Insert(tmp, tree);
}
qx(tree);
printf("\n");
zx(tree);
printf("\n");
hx(tree);
printf("\n");
}
}