您的位置:首页 > 其它

LeetCode – Refresh – Construct Binary Tree from Inorder and Postorder Traversal

2015-03-19 05:27 316 查看
For this problem just need to know the structure of two traversal.

1. It is hard to find the root node in the inorder traversal but it is easy in postorder. The last one in post order is the root.

2. At same time, you can not figure out what is the boundary for left branch and right branch in post order. But you can do it in inorder.

/**
* 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 *getTree(vector<int> &iv, vector<int> &pv, int ist, int ied, int pst, int ped) {
if (ist > ied) return NULL;
int current = -1, len = 0;
for (int i = ist; i <= ied; i++) {
if (pv[ped] == iv[i]) {
current = i;
break;
}
}
len = current - ist;
TreeNode *root = new TreeNode(pv[ped]);
root->left = getTree(iv, pv, ist, current-1, pst, pst+len-1);
root->right = getTree(iv, pv, current+1, ied, pst+len, ped-1);
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if (inorder.size() == 0 || inorder.size() != postorder.size()) return NULL;
return getTree(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: