problem:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
题意:给定二叉树的中序遍历序列和后续遍历序列,构建这棵二叉树,也很经典
thinking:
(1)这种类型的题,要举个例子找出其规律。对于满二叉树(1,2,3,4,5,6,7),中序遍历:4,2,5,1,6,3,7 后续遍历:4,5,2,6,7,3,1
首先根结点1在后续遍历序列的最后一个位置上,再在中序遍历序列中find 1的位置,1之前的为左子树,1 之后的为右子树。知道子树节点数量后,
同样对于后续遍历序列也可以划分左右子树。
(2)递归重复上述过程
code:
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if (inorder.size() == 0)
return NULL;
return make(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
}
protected:
template<class it>
TreeNode *make(it pFirst,it pLast,it qFirst,it qLast)
{
if(pFirst==pLast)
return NULL;
it loc1 = qLast-1;
int a = *loc1;
it loc2=find(pFirst,pLast,a);
int left_size=loc2-pFirst;
TreeNode *root=new TreeNode(a);
root->left=make(pFirst,loc2,qFirst,qFirst+left_size);
root->right=make(loc2+1,pLast,qFirst+left_size,qLast-1);
return root;
}
};