File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments