|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * class TreeNode { |
| 4 | + * val: number |
| 5 | + * left: TreeNode | null |
| 6 | + * right: TreeNode | null |
| 7 | + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { |
| 8 | + * this.val = (val===undefined ? 0 : val) |
| 9 | + * this.left = (left===undefined ? null : left) |
| 10 | + * this.right = (right===undefined ? null : right) |
| 11 | + * } |
| 12 | + * } |
| 13 | + */ |
| 14 | + |
| 15 | +// 37ms |
| 16 | +// Time Complexity: O(n^2), n: ๋
ธ๋์ ์ |
| 17 | +// Space Complexity: O(h), h: ํธ๋ฆฌ์ ๋์ด |
| 18 | +function buildTree(preorder: number[], inorder: number[]): TreeNode | null { |
| 19 | + if (preorder.length === 0 || inorder.length === 0) return null; |
| 20 | + |
| 21 | + const root = preorder[0]; |
| 22 | + |
| 23 | + const rootIdx = inorder.findIndex((el) => el === root); |
| 24 | + |
| 25 | + const leftInorder = inorder.slice(0, rootIdx); |
| 26 | + const leftPreorder = preorder.slice(1, leftInorder.length + 1); |
| 27 | + |
| 28 | + const rightInorder = inorder.slice(rootIdx + 1); |
| 29 | + const rightPreorder = preorder.slice(leftInorder.length + 1); |
| 30 | + |
| 31 | + const rootNode = new TreeNode(root); |
| 32 | + |
| 33 | + rootNode.left = buildTree(leftPreorder, leftInorder); |
| 34 | + rootNode.right = buildTree(rightPreorder, rightInorder); |
| 35 | + |
| 36 | + return rootNode; |
| 37 | +} |
| 38 | + |
| 39 | +// 3ms |
| 40 | +// Time Complexity: O(n), n: ๋
ธ๋์ ์ |
| 41 | +// Space Complexity: O(n), n: ๋
ธ๋์ ์ |
| 42 | +function buildTree(preorder: number[], inorder: number[]): TreeNode | null { |
| 43 | + if (preorder.length === 0 || inorder.length === 0) return null; |
| 44 | + |
| 45 | + const indexMap = new Map<number, number>(); |
| 46 | + inorder.forEach((node, idx) => indexMap.set(node, idx)); |
| 47 | + |
| 48 | + const build = (preStart: number, preEnd: number, inStart: number, inEnd: number): TreeNode | null => { |
| 49 | + if (preStart > preEnd || inStart > inEnd) return null; |
| 50 | + |
| 51 | + const rootVal = preorder[preStart]; |
| 52 | + const rootIdx = indexMap.get(rootVal); |
| 53 | + |
| 54 | + const leftSize = rootIdx - inStart; |
| 55 | + |
| 56 | + const root = new TreeNode(rootVal); |
| 57 | + root.left = build(preStart + 1, preStart + leftSize, inStart, rootIdx - 1); |
| 58 | + root.right = build(preStart + leftSize + 1, preEnd, rootIdx + 1, inEnd); |
| 59 | + |
| 60 | + return root; |
| 61 | + }; |
| 62 | + |
| 63 | + return build(0, preorder.length - 1, 0, inorder.length - 1); |
| 64 | +} |
0 commit comments