利用带空的先序遍历结果建立二叉树:
tree *creat(tree *root)
{
char ch;
scanf("%c",&ch);
if(ch==',') root=NULL;
else
{
root=new tree;
root->data=ch;
root->left=creat(root->left);
root->right=creat(root->right);
}
return root;
}
不带空的先序和中序遍历结果建立二叉树:
tree *build(int ps,int is,int n)
//preorder为先序遍历序列、inorder为中序遍历序列、ps为先序的起始位置、is为中序的起始位置、n为序列元素个数
{
int k;
for(k=is;k<=is+n-1;k++)
if(preorder[ps]==inorder[k])
break;
tree *t=new tree;
t->data=preorder[ps];
if(k==is) t->left=NULL;
else t->left=build(ps+1,is,k-is);//递归创建左
if(k==is+n-1) t->right=NULL;
else t->right=build(ps+1+(k-is),k+1,n-(k-is)-1); //去掉根节点,去掉左边的
return t;
}