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

[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-01-17 20:47:15      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 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 *buildTree(vector<int> &inorder, vector<int> &postorder) {
13         if (inorder.empty() || postorder.empty())
14             return NULL;
15             return buildTree(inorder.begin(), inorder.end() - 1, postorder.begin(), postorder.end() - 1);
16         }
17     template<typename Iter>
18     TreeNode* buildTree(Iter inBegin, Iter inEnd, Iter postBegin, Iter postEnd) {
19         if (inBegin > inEnd) return nullptr;
20         if (postBegin > postEnd) return nullptr;
21         
22         TreeNode *root = new TreeNode(*postEnd);
23         Iter in_root_pos = find(inBegin, inEnd, *postEnd);
24         int left_length = in_root_pos - inBegin;
25         root->left = buildTree(inBegin, in_root_pos - 1, postBegin, postBegin + left_length - 1);
26         root->right = buildTree(in_root_pos + 1, inEnd, postBegin + left_length, postEnd - 1);
27         
28         return root;
29     }
30 };

 

[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/vincently/p/4230944.html

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