Given inorder and postorder traversal of a tree, construct the binary tree.
给后序序列和中序序列,求二叉树。
这个怎么说呢,和上一道题如出一辙,只不过是顺序变了,简单!
TreeNode * f(vector<int> &inorder, vector<int> &postorder, int inl,int inr,int postl, int postr){
int n=inr-inl+1;
if(n==0)
return NULL;
int i=0;
for(;i<=n-1;i++){
if(inorder[inl+i]==postorder[postr])
break;
}
TreeNode * root=new TreeNode(inorder[inl+i]);
root->left=f(inorder,postorder,inl,inl+i-1,postl,postl+i-1);
root->right=f(inorder,postorder,inl+i+1,inr,postl+i,postr-1);
return root;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
return f(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
}
本文介绍了一种使用给定的中序和后序遍历序列来构造二叉树的方法。通过递归地查找根节点,并利用中序遍历来划分左右子树,最终构建完整的二叉树结构。
89

被折叠的 条评论
为什么被折叠?



