Skip to content

Commit d0bb6a9

Browse files
committed
add buildTree.cpp
1 parent 5789a2a commit d0bb6a9

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

C++/buildTreeWithPostOrder.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(logn)
3+
4+
/**
5+
* Definition for binary tree
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
16+
return buildTree(begin(inorder), end(inorder), begin(postorder), end(postorder));
17+
}
18+
private:
19+
template<typename InputIterator>
20+
TreeNode *buildTree(InputIterator in_first, InputIterator in_last, InputIterator post_first, InputIterator post_last) {
21+
if(in_first == in_last)
22+
return NULL;
23+
if(post_first == post_last)
24+
return NULL;
25+
26+
auto root = new TreeNode(*prev(post_last));
27+
auto inRootPos = find(in_first, in_last, *prev(post_last));
28+
auto leftSize = distance(in_first, inRootPos);
29+
root->left = buildTree(in_first, inRootPos, post_first, next(post_first, leftSize));
30+
root->right = buildTree(next(inRootPos), in_last, next(post_first, leftSize), prev(post_last));
31+
32+
return root;
33+
}
34+
35+
};

C++/buildTreeWithPreOrder.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(logn)
3+
4+
/**
5+
* Definition for binary tree
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
16+
return buildTree(begin(preorder), end(preorder), begin(inorder), end(inorder));
17+
}
18+
19+
private:
20+
template<typename InputIterator>
21+
TreeNode* buildTree(InputIterator pre_first, InputIterator pre_last, InputIterator in_first, InputIterator in_last) {
22+
if(pre_first == pre_last)
23+
return NULL;
24+
if(in_first == in_last)
25+
return NULL;
26+
27+
auto root = new TreeNode(*pre_first);
28+
auto inRootPos = find(in_first, in_last, *pre_first);
29+
auto leftSize = distance(in_first, inRootPos);
30+
root->left = buildTree(next(pre_first), next(pre_first, leftSize + 1), in_first, inRootPos);
31+
root->right = buildTree(next(pre_first, leftSize + 1), pre_last, next(inRootPos), in_last);
32+
33+
return root;
34+
}
35+
};

0 commit comments

Comments
 (0)