We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 587c005 commit 741a5b6Copy full SHA for 741a5b6
construct-binary-tree-from-preorder-and-inorder-traversal/nhistory.js
@@ -0,0 +1,17 @@
1
+var buildTree = function (preorder, inorder) {
2
+ // Edge case: if either preorder or inorder is empty, return null
3
+ if (!preorder.length || !inorder.length) return null;
4
+
5
+ // The first element in preorder is the root of the tree
6
+ // Find the index of the root in the inorder array
7
+ const root = new TreeNode(preorder[0]);
8
+ const mid = inorder.indexOf(root.val);
9
10
+ root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid));
11
+ root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1));
12
13
+ return root;
14
+};
15
16
+// TC: O(n)
17
+// SC: O(n)
0 commit comments