Skip to content

Commit 911ee8e

Browse files
committed
Solution: Construct Binary Tree from Preorder and Inorder Traversal
1 parent 8efcb4f commit 911ee8e

File tree

1 file changed

+49
-0
lines changed
  • construct-binary-tree-from-preorder-and-inorder-traversal

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* For the number of given nodes N,
3+
*
4+
* Time complexity: O(N)
5+
*
6+
* Space complexity: O(N) at worst
7+
*/
8+
9+
/**
10+
* Definition for a binary tree node.
11+
* struct TreeNode {
12+
* int val;
13+
* TreeNode *left;
14+
* TreeNode *right;
15+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
16+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
17+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
18+
* };
19+
*/
20+
class Solution {
21+
public:
22+
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
23+
unordered_map<int, int> inorder_index_map;
24+
stack<TreeNode*> tree_stack;
25+
26+
for (int i = 0; i < inorder.size(); i++) inorder_index_map[inorder[i]] = i;
27+
28+
TreeNode* root = new TreeNode(preorder[0]);
29+
tree_stack.push(root);
30+
31+
for (int i = 1; i < preorder.size(); i++) {
32+
TreeNode* curr = new TreeNode(preorder[i]);
33+
34+
if (inorder_index_map[curr->val] < inorder_index_map[tree_stack.top()->val]) {
35+
tree_stack.top()->left = curr;
36+
} else {
37+
TreeNode* parent;
38+
while (!tree_stack.empty() && inorder_index_map[curr->val] > inorder_index_map[tree_stack.top()->val]) {
39+
parent = tree_stack.top();
40+
tree_stack.pop();
41+
}
42+
parent->right = curr;
43+
}
44+
tree_stack.push(curr);
45+
}
46+
47+
return root;
48+
}
49+
};

0 commit comments

Comments
 (0)