码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-03-19 06:19:44      阅读:119      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!