Skip to content

Commit

Permalink
4. construct-binary-tree-from-preorder-and-inorder-traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
whewchews committed Aug 23, 2024
1 parent 31b7ee6 commit 8f4e343
Showing 1 changed file with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}

function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
// build ํ•จ์ˆ˜๊ฐ€ ๊ฐ ๋…ธ๋“œ๋งˆ๋‹ค ํ˜ธ์ถœ๋จ(N) * ๊ฐ ๋…ธ๋“œ๋งˆ๋‹ค shift, indexOf ์ˆ˜ํ–‰(N) = O(N^2)
function build(preorder, inorder) {
if (inorder.length) {
// TC: O(N)
const idx = inorder.indexOf(preorder.shift());
const root = new TreeNode(inorder[idx]);

root.left = build(preorder, inorder.slice(0, idx));
root.right = build(preorder, inorder.slice(idx + 1));

return root;
}
return null;
}

return build(preorder, inorder);
}

// TC: O(N^2)
// SC: O(N^2)

0 comments on commit 8f4e343

Please sign in to comment.