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