https://leetcode.com/problems/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 a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
TreeNode* helper(vector<int> &in, int inLow, int inHigh, vector<int> &post, int postLow, int postHigh)
{
if (inLow > inHigh)
return NULL;
TreeNode* root = new TreeNode(post[postHigh]);
int rootIndex = 0;
for (int i = inLow; i <= inHigh; i++)
{
if (in[i] == post[postHigh])
{
rootIndex = i;
break;
}
}
root->left = helper(in, inLow, rootIndex - 1, post, postLow, rootIndex - 1 - inLow + postLow);
root->right = helper(in, rootIndex + 1, inHigh, post, postHigh - inHigh + rootIndex, postHigh - 1);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
{
return helper(inorder,0, inorder.size()-1, postorder, 0, postorder.size()-1);
}
};
测试用例
inorder:[4,7,2,1,5,3,8,6]
postorder:[7,4,2,5,8,6,3,1]
结果:
[1,2,3,4,null,5,6,null,7,null,null,8]