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

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

时间:2015-03-19 06:20:26      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

Only different with preorder and postorder is that the root start from the beginning for preorder.

 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[pst] == iv[i]) {
17                 current = i;
18                 break;
19             }
20         }
21         len = current - ist;
22         TreeNode *root = new TreeNode(pv[pst]);
23         root->left = getTree(iv, pv, ist, current-1, pst+1, pst+len);
24         root->right = getTree(iv, pv, current+1, ied, pst+len+1, ped);
25     }
26     
27     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
28         if (inorder.size() == 0 || inorder.size() != preorder.size()) return NULL;
29         return getTree(inorder, preorder, 0, inorder.size()-1, 0, preorder.size()-1);
30     }
31 };

 

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

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4349276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!