首页 > 其他 > 详细

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

时间:2015-03-19 06:18:41      阅读:212      评论:0      收藏:0      [点我收藏+]

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.

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode *getTree(vector<int> &iv, vector<int> &pv, int ist, int ied, int pst, int ped) {
13         if (ist > ied) return NULL;
14         int current = -1, len = 0;
15         for (int i = ist; i <= ied; i++) {
16             if (pv[ped] == iv[i]) {
17                 current = i;
18                 break;
19             }
20         }
21         len = current - ist;
22         TreeNode *root = new TreeNode(pv[ped]);
23         root->left = getTree(iv, pv, ist, current-1, pst, pst+len-1);
24         root->right = getTree(iv, pv, current+1, ied, pst+len, ped-1);
25     }
26     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
27         if (inorder.size() == 0 || inorder.size() != postorder.size()) return NULL;
28         return getTree(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1);
29     }
30 };

 

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

原文:http://www.cnblogs.com/shuashuashua/p/4349275.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!