|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ |
| 3 | + * Definition for a binary tree node. |
| 4 | + * function TreeNode(val, left, right) { |
| 5 | + * this.val = (val===undefined ? 0 : val) |
| 6 | + * this.left = (left===undefined ? null : left) |
| 7 | + * this.right = (right===undefined ? null : right) |
| 8 | + * } |
| 9 | + */ |
| 10 | +/** |
| 11 | + * @param {number[]} preorder |
| 12 | + * @param {number[]} inorder |
| 13 | + * @return {TreeNode} |
| 14 | + */ |
| 15 | +var buildTree = function (preorder, inorder) { |
| 16 | + // ํด์๋งต์ ๋ง๋ค์ด ์ค์ ์ํ์ ๊ฐ -> ์ธ๋ฑ์ค๋ฅผ ๋น ๋ฅด๊ฒ ์ฐพ์ ์ ์๋๋ก ํจ |
| 17 | + const inorderMap = new Map(); |
| 18 | + inorder.forEach((val, idx) => { |
| 19 | + inorderMap.set(val, idx); |
| 20 | + }); |
| 21 | + |
| 22 | + // preorder๋ฅผ ์ํํ ์ธ๋ฑ์ค |
| 23 | + let preorderIndex = 0; |
| 24 | + |
| 25 | + /** |
| 26 | + * ์ฌ๊ท ํจ์: ํ์ฌ ์๋ธํธ๋ฆฌ์ ์ค์ ์ํ ๊ตฌ๊ฐ(start ~ end)์ ๊ธฐ๋ฐ์ผ๋ก ํธ๋ฆฌ๋ฅผ ๋ง๋ ๋ค. |
| 27 | + */ |
| 28 | + function arrayToTree(left, right) { |
| 29 | + // ์ข
๋ฃ ์กฐ๊ฑด: ๊ตฌ๊ฐ์ด ์๋ชป๋๋ฉด ๋
ธ๋๊ฐ ์์ |
| 30 | + if (left > right) return null; |
| 31 | + |
| 32 | + // preorder์์ ํ์ฌ ๋ฃจํธ ๊ฐ ์ ํ |
| 33 | + const rootVal = preorder[preorderIndex]; |
| 34 | + preorderIndex++; // ๋ค์ ํธ์ถ์ ์ํด ์ธ๋ฑ์ค ์ฆ๊ฐ |
| 35 | + |
| 36 | + // ํ์ฌ ๋
ธ๋ ์์ฑ |
| 37 | + const root = new TreeNode(rootVal); |
| 38 | + |
| 39 | + // ๋ฃจํธ ๊ฐ์ ์ค์ ์ํ ์ธ๋ฑ์ค ์ฐพ๊ธฐ |
| 40 | + const index = inorderMap.get(rootVal); |
| 41 | + |
| 42 | + // ์ผ์ชฝ ์๋ธํธ๋ฆฌ์ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ์ฌ๊ท์ ์ผ๋ก ์์ฑ |
| 43 | + root.left = arrayToTree(left, index - 1); |
| 44 | + root.right = arrayToTree(index + 1, right); |
| 45 | + |
| 46 | + return root; |
| 47 | + } |
| 48 | + |
| 49 | + // ์ ์ฒด inorder ๋ฒ์๋ก ์์ |
| 50 | + return arrayToTree(0, inorder.length - 1); |
| 51 | +}; |
0 commit comments