From 8f4e3438f854052e245417d7e83ee5643d9712e8 Mon Sep 17 00:00:00 2001 From: whewchews Date: Sat, 24 Aug 2024 02:24:20 +0900 Subject: [PATCH] 4. construct-binary-tree-from-preorder-and-inorder-traversal --- .../whewchews.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 construct-binary-tree-from-preorder-and-inorder-traversal/whewchews.ts diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/whewchews.ts b/construct-binary-tree-from-preorder-and-inorder-traversal/whewchews.ts new file mode 100644 index 000000000..4d54a44f6 --- /dev/null +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/whewchews.ts @@ -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)