Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(inorder.size()==0)
return NULL;
TreeNode *root=Build(0,inorder.size()-1,0,postorder.size()-1,inorder,postorder);
return root;
}
TreeNode *Build(int li,int ri,int lp,int rp,vector<int> &inorder , vector<int> &postorder){
int i;
if(li>ri)
return NULL;
TreeNode *left,*right;
TreeNode *root=new TreeNode(postorder[rp]);
for(i=li ; i<=ri ;i++)
if(inorder[i]==postorder[rp])
break;
int ca=i-li;//left num of numbers
int cb=ri-i;//right num of number
left=Build(li,i-1,lp,lp+ca-1,inorder,postorder);
right=Build(i+1,ri,lp+ca,rp-1,inorder,postorder);
root->left=left;
root->right=right;
return root;
}
};
本文介绍了一种通过给定的中序遍历和后序遍历序列来构建二叉树的方法。该方法首先检查输入序列的有效性,然后递归地构建二叉树结构,确保每个节点的左右子树与其在中序和后序遍历序列中的位置相匹配。
795

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



