Skip to content

Commit e4afccc

Browse files
authored
construct binary tree from preorder and inorder traversal solution
Added time and space complexity comments for clarity.
1 parent 82cfccf commit e4afccc

File tree

1 file changed

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

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* int val;
5+
* TreeNode? left;
6+
* TreeNode? right;
7+
* TreeNode([this.val = 0, this.left, this.right]);
8+
* }
9+
*/
10+
class Solution {
11+
TreeNode? buildTree(List<int> preorder, List<int> inorder) {
12+
int i = 1, j = 0;
13+
final root = TreeNode(preorder[0]);
14+
final stack = [root]; // T(n) = S(n) = O(n)
15+
while (i != preorder.length) {
16+
var u = stack.last;
17+
if (u.val != inorder[j]) {
18+
u.left = TreeNode(preorder[i++]);
19+
stack.add(u.left!);
20+
continue;
21+
}
22+
while (! stack.isEmpty && stack.last.val == inorder[j]) {
23+
u = stack.removeLast();
24+
j++;
25+
}
26+
u.right = TreeNode(preorder[i++]);
27+
stack.add(u.right!);
28+
}
29+
return root;
30+
}
31+
}

0 commit comments

Comments
 (0)