106. Construct Binary Tree from Inorder and Postorder Traversal
题目描述
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
代码实现
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
int m = inorder.size();
int n = postorder.size();
if(m!=n || m==0)
return nullptr;
return buildTreeCore(inorder,0,n-1,postorder,0,n-1);
}
TreeNode *buildTreeCore(vector<int> &inorder,int in_l,int in_r,vector<int> &postorder,int post_l,int post_r)
{
if(in_l>in_r)
return nullptr;
TreeNode * root = new TreeNode(postorder[post_r]);
root->left = nullptr;
root->right = nullptr;
int theRoot = in_l;
while(inorder[theRoot]!=root->val)theRoot++;
root->left = buildTreeCore(inorder,in_l,theRoot-1,postorder,post_l,post_l+theRoot-in_l-1);
root->right = buildTreeCore(inorder,theRoot+1,in_r,postorder,post_l+theRoot-in_l,post_r-1);
return root;
}
};