您的位置:首页 > 其它

LeetCode-106.Construct Binary Tree from Inorder and Postorder Traversal

2016-06-26 22:03 369 查看
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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode