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) {
if (postorder.empty() || inorder.empty()) return NULL;
TreeNode *root = new TreeNode(*(postorder.end() - 1));
vector<int>::iterator it;
for (it = inorder.begin(); it != inorder.end(); ++it)
{
if (*it == *(postorder.end() - 1))
break;
}
postorder.pop_back();
vector<int> left, right;
left.insert(left.begin(), inorder.begin(), it);
right.insert(right.begin(), it + 1, inorder.end());
root->right = buildTree(right, postorder);
root->left = buildTree(left, postorder);
return root;
}
};