|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +class Solution { |
| 4 | + int[][] answer; |
| 5 | + int idx; |
| 6 | + |
| 7 | + public int[][] solution(int[][] nodeinfo) { |
| 8 | + int n = nodeinfo.length; |
| 9 | + List<Node> nodes = new ArrayList<>(); |
| 10 | + |
| 11 | + for (int i = 0; i < n; i++) { |
| 12 | + nodes.add(new Node(i + 1, nodeinfo[i][0], nodeinfo[i][1])); |
| 13 | + } |
| 14 | + |
| 15 | + nodes.sort((a, b) -> { |
| 16 | + if (a.y == b.y) return a.x - b.x; |
| 17 | + return b.y - a.y; |
| 18 | + }); |
| 19 | + |
| 20 | + Node root = nodes.get(0); |
| 21 | + for (int i = 1; i < nodes.size(); i++) { |
| 22 | + insertNode(root, nodes.get(i)); |
| 23 | + } |
| 24 | + |
| 25 | + answer = new int[2][n]; |
| 26 | + idx = 0; |
| 27 | + preOrder(root); |
| 28 | + idx = 0; |
| 29 | + postOrder(root); |
| 30 | + |
| 31 | + return answer; |
| 32 | + } |
| 33 | + |
| 34 | + private void insertNode(Node parent, Node child) { |
| 35 | + if (child.x < parent.x) { |
| 36 | + if (parent.left == null) parent.left = child; |
| 37 | + else insertNode(parent.left, child); |
| 38 | + } else { |
| 39 | + if (parent.right == null) parent.right = child; |
| 40 | + else insertNode(parent.right, child); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // 전위 순회 |
| 45 | + private void preOrder(Node node) { |
| 46 | + if (node == null) return; |
| 47 | + answer[0][idx++] = node.id; |
| 48 | + preOrder(node.left); |
| 49 | + preOrder(node.right); |
| 50 | + } |
| 51 | + |
| 52 | + // 후위 순회 |
| 53 | + private void postOrder(Node node) { |
| 54 | + if (node == null) return; |
| 55 | + postOrder(node.left); |
| 56 | + postOrder(node.right); |
| 57 | + answer[1][idx++] = node.id; |
| 58 | + } |
| 59 | + |
| 60 | + class Node { |
| 61 | + int id, x, y; |
| 62 | + Node left, right; |
| 63 | + |
| 64 | + public Node(int id, int x, int y) { |
| 65 | + this.id = id; |
| 66 | + this.x = x; |
| 67 | + this.y = y; |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments