Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [,,,,]
postorder = [,,,,]
Return the following binary tree:
/ \ / \
中序、后序遍历得到二叉树,可以知道每一次新数组的最后一个数为当时子树的根节点,每次根据中序遍历的根节点的左右两边确定左右子树,再对应后序的左右子树,不停递归得到根节点,可以建立二叉树。每次由循环得到根节点在中序数组中坐标i
由中序遍历知:每一次inorder的左子树范围[ileft,i-1],右子树范围[i+1,iright]
由后序遍历知:每一次postorder的左子树范围[pleft,pleft+i-ileft-1],右子树范围[pleft+i-ileft,pright-1]。C++
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTree(inorder,,inorder.size()-,postorder,,postorder.size()-);
} TreeNode* buildTree(vector<int>& inorder,int ileft,int iright,vector<int>& postorder,int pleft,int pright){
if(ileft>iright||pleft>pright)
return NULL;
TreeNode* root=new TreeNode(postorder[pright]);
int i=;
for(i=ileft;i<=iright;i++){
if(inorder[i]==postorder[pright])
break;
}
root->left=buildTree(inorder,ileft,i-,postorder,pleft,pleft+i-ileft-);
root->right=buildTree(inorder,i+,iright,postorder,pleft+i-ileft,pright-);
return root;
}