过程:
1.定义二叉树结构与静态构造
struct Node{
Node* rchild;
Node* lchild;
int value;
}tree[100];
int size;
Node* create()
{
tree[size].rchild=tree[size].lchild=NULL;
return &tree[size++];
}
2.三种递归遍历实现
void postorder(Node *root)
{
if(root==NULL)
return;
postorder(root->lchild);
postorder(root->rchild);
cout<<root->value<<" ";
}
void inorder(Node *root)
{
if (root==NULL)
return;
inorder(root->lchild);
cout<<root->value<<" ";
inorder(root->rchild);
}
void preorder(Node *root)
{
if (root==NULL)
return;
cout<<root->value<<" ";
preorder(root->lchild);
preorder(root->rchild);
}
Node *insert(Node* root,int x)
{
if (root==NULL) {
root=create();
root->value=x;
}
else if (x<root->value) {
root->lchild=insert(root->lchild, x);
}
else if (x>root->value){
root->rchild=insert(root->rchild, x);
}
return root;
}
4.主函数的实现
int main()
{
int n;
while (cin>>n) {
size=0;
Node* root=NULL;
for (int i=0; i<n; i++) {
int temp;
cin>>temp;
root=insert(root, temp);
}
preorder(root);
cout<<endl;
inorder(root);
cout<<endl;
postorder(root);
cout<<endl;
}
}