根据中序遍历和后序遍历树构造二叉树
注意事项
你可以假设树中不存在相同数值的节点
样例
给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]
返回如下的树:
2
/ \
1 3
题目链接:http://www.lintcode.com/zh-cn/problem/construct-binary-tree-from-inorder-and-postorder-traversal/
后序遍历的最后一个数为二叉树的根结点,在中序遍历中找到这个“根结点”,将中序遍历分为两部分,左半部分为根的左子树,右半部分为根的右子树。再把这两部分分别当成一个完整的树,于是使用递归来构造这棵二叉树:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
*@param inorder : A list of integers that inorder traversal of a tree
*@param postorder : A list of integers that postorder traversal of a tree
*@return : Root of a tree
*/
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
// write your code here
if (inorder.size() == 0) return NULL;
return build(inorder,postorder,0,inorder.size() - 1,0,postorder.size() - 1);
}
TreeNode *build(vector<int> &inorder,vector<int> postorder,int startin,int endin,int startpost,int endpost) {
if (startin > endin) return NULL;
TreeNode *root = new TreeNode(postorder[endpost]);
int divide = 0;
while (divide <= endin && inorder[divide] != root->val) divide++;
int offset = divide - startin - 1;
root->left = build(inorder,postorder,startin,startin + offset,startpost,startpost + offset);
root->right = build(inorder,postorder,divide + 1,endin,startpost + offset + 1,endpost - 1);
return root;
}
};