您的位置:首页 > 其它

[Leetcode 79] 106 Construct Binary Tree from Inorder and Postorder Traversal

2013-07-23 02:21 741 查看
Problem:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Analysis:

This problem is the same as the former one of reconstructing the binary tree with inorder and preorder traversal array.

The only difference is that now the root is always at the end of the given array.

A comparison of the two problem's solving is as follows:

Post & In:

t->left = build(in, is, idx-1, post, ps, ps+idx-is-1);
t->right = build(in, idx+1, ie, post, ps+idx-is, pe-1);

Pre & In:

t->left = fun(in, is, idx-1, pre, ps+1, ps+idx-is);

t->right = fun(in, idx+1, ie, pre, ps+idx-is+1, pe);

We can see that the sub-array for in is the same of the two solution. The difference comes from the latter part.

Code:

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return build(inorder, 0, inorder.size()-1,
postorder, 0, postorder.size()-1);
}

private:
TreeNode *build(vector<int> &in, int is, int ie,
vector<int> &post, int ps, int pe) {
if (is > is || ps > pe)
return NULL;

TreeNode *t = new TreeNode(post[pe]);
int idx = search(in, is, ie, post[pe]);

t->left = build(in, is, idx-1, post, ps, ps+idx-is-1);
t->right = build(in, idx+1, ie, post, ps+idx-is, pe-1);

return t;
}

int search(vector<int> &in, int s, int e, int v) {
int idx;
for (idx=s; idx<=e; idx++)
if (in[idx] == v)
break;

return idx;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐