|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * public class TreeNode { |
| 4 | + * int val; |
| 5 | + * TreeNode left; |
| 6 | + * TreeNode right; |
| 7 | + * TreeNode() {} |
| 8 | + * TreeNode(int val) { this.val = val; } |
| 9 | + * TreeNode(int val, TreeNode left, TreeNode right) { |
| 10 | + * this.val = val; |
| 11 | + * this.left = left; |
| 12 | + * this.right = right; |
| 13 | + * } |
| 14 | + * } |
| 15 | + */ |
| 16 | + |
| 17 | +import java.util.*; |
| 18 | + |
| 19 | +class Solution { |
| 20 | + private int preIdx = 0; |
| 21 | + private Map<Integer, Integer> inPos = new HashMap<>(); |
| 22 | + |
| 23 | + public TreeNode buildTree(int[] preorder, int[] inorder) { |
| 24 | + // inorder 값의 위치를 미리 저장: value -> index |
| 25 | + for (int i = 0; i < inorder.length; i++) { |
| 26 | + inPos.put(inorder[i], i); |
| 27 | + } |
| 28 | + |
| 29 | + return build(preorder, 0, inorder.length - 1); |
| 30 | + } |
| 31 | + |
| 32 | + private TreeNode build(int[] preorder, int inLeft, int inRight) { |
| 33 | + // inorder 구간이 비면 서브트리 없음 |
| 34 | + if (inLeft > inRight) return null; |
| 35 | + |
| 36 | + // preorder에서 현재 루트 꺼내기 |
| 37 | + int rootVal = preorder[preIdx++]; |
| 38 | + TreeNode root = new TreeNode(rootVal); |
| 39 | + |
| 40 | + // inorder에서 루트 위치 찾기 |
| 41 | + int k = inPos.get(rootVal); |
| 42 | + |
| 43 | + // 왼쪽 서브트리: inorder[inLeft .. k-1] |
| 44 | + root.left = build(preorder, inLeft, k - 1); |
| 45 | + |
| 46 | + // 오른쪽 서브트리: inorder[k+1 .. inRight] |
| 47 | + root.right = build(preorder, k + 1, inRight); |
| 48 | + |
| 49 | + return root; |
| 50 | + } |
| 51 | +} |
0 commit comments