|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +class Solution { |
| 5 | + // ๋น ๋ฅธ ์กฐํ๋ฅผ ์ํด inorder์ ๊ฐ๊ณผ ์ธ๋ฑ์ค๋ฅผ ์ ์ฅํ Map |
| 6 | + private Map<Integer, Integer> inMap; |
| 7 | + |
| 8 | + public TreeNode buildTree(int[] preorder, int[] inorder) { |
| 9 | + inMap = new HashMap<>(); |
| 10 | + for (int i = 0; i < inorder.length; i++) { |
| 11 | + inMap.put(inorder[i], i); |
| 12 | + } |
| 13 | + |
| 14 | + return construct(preorder, 0, preorder.length - 1, 0, inorder.length - 1); |
| 15 | + } |
| 16 | + |
| 17 | + private TreeNode construct(int[] preorder, int preStart, int preEnd, int inStart, int inEnd) { |
| 18 | + // ๊ธฐ์ ์กฐ๊ฑด: ๋ ์ด์ ์ฒ๋ฆฌํ ๋
ธ๋๊ฐ ์๋ ๊ฒฝ์ฐ |
| 19 | + if (preStart > preEnd || inStart > inEnd) { |
| 20 | + return null; |
| 21 | + } |
| 22 | + |
| 23 | + // 1. preorder์ ํ์ฌ ๊ตฌ๊ฐ ์ฒซ ๋ฒ์งธ ์์๊ฐ ๋ฃจํธ ๋
ธ๋์
๋๋ค. |
| 24 | + int rootVal = preorder[preStart]; |
| 25 | + TreeNode root = new TreeNode(rootVal); |
| 26 | + |
| 27 | + // 2. inorder์์ ๋ฃจํธ์ ์์น๋ฅผ ์ฐพ์ ์ผ์ชฝ/์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ ๋ฒ์๋ฅผ ๋๋๋๋ค. |
| 28 | + int rootIdx = inMap.get(rootVal); |
| 29 | + int leftSize = rootIdx - inStart; // ์ผ์ชฝ ์๋ธํธ๋ฆฌ์ ํฌํจ๋ ๋
ธ๋ ๊ฐ์ |
| 30 | + |
| 31 | + // 3. ์ฌ๊ท์ ์ผ๋ก ์ผ์ชฝ ์์ ๋
ธ๋๋ค์ ์ฐ๊ฒฐํฉ๋๋ค. |
| 32 | + // preorder ๋ฒ์: ๋ฃจํธ ๋ค์(preStart + 1)๋ถํฐ ๊ฐ์(leftSize)๋งํผ |
| 33 | + // inorder ๋ฒ์: ์๋ ์์์ ๋ถํฐ ๋ฃจํธ ์(rootIdx - 1)๊น์ง |
| 34 | + root.left = construct(preorder, preStart + 1, preStart + leftSize, |
| 35 | + inStart, rootIdx - 1); |
| 36 | + |
| 37 | + // 4. ์ฌ๊ท์ ์ผ๋ก ์ค๋ฅธ์ชฝ ์์ ๋
ธ๋๋ค์ ์ฐ๊ฒฐํฉ๋๋ค. |
| 38 | + // preorder ๋ฒ์: ์ผ์ชฝ ์๊ตฌ๋ค ๋๋ ์ง์ ๋ค์(preStart + leftSize + 1)๋ถํฐ ๋๊น์ง |
| 39 | + // inorder ๋ฒ์: ๋ฃจํธ ๋ค์(rootIdx + 1)๋ถํฐ ๋๊น์ง |
| 40 | + root.right = construct(preorder, preStart + leftSize + 1, preEnd, |
| 41 | + rootIdx + 1, inEnd); |
| 42 | + |
| 43 | + return root; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | + |
0 commit comments