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.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
解析
递归构建左右子树即可。但是在后序遍历的时候要注意下标问题。
代码
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(postorder.empty() || inorder.empty())
return NULL;
int val = postorder[postorder.size()-1];
int size = inorder.size();
TreeNode* root = new TreeNode(val);
vector<int> leftpost;
vector<int> rightpost;
vector<int> leftin;
vector<int> rightin;
int index;
for(int i=0;i<size;i++){
if(inorder[i] == val){
index = i;
break;
}
}
for(int i=0;i<index;i++){
leftin.push_back(inorder[i]);
leftpost.push_back(postorder[i]);
}
for(int i=index+1;i<size;i++){
rightin.push_back(inorder[i]);
rightpost.push_back(postorder[i-1]); //postorder的下标需要思考一下,不要理所当然。
}
root->left = buildTree(leftin, leftpost);
root->right = buildTree(rightin, rightpost);
return root;
}
};