https://programmers.co.kr/learn/courses/30/lessons/42892
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
import java.util.*; class Solution { class Tree{ Tree right; Tree left; int x=0; int y=0; int index=0; Tree(int x,int y,int index){ this.x=x; this.y=y; this.index=index; } } public int[][] solution(int[][] nodeinfo) { int[][] answer =new int[2][nodeinfo.length]; int index=0; Tree[] trees= new Tree[nodeinfo.length]; for (int i = 0; i < nodeinfo.length; i++) { trees[i]=new Tree(nodeinfo[i][0],nodeinfo[i][1],++index); } Arrays.sort(trees, new Comparator<Tree>() { @Override public int compare(Tree o1, Tree o2) { int x1=o1.x;int x2=o2.x;int y1=o1.y;int y2=o2.y; if(y1<y2) return 1; else if(y1>y2) return -1; else if(y1==y2){ if(x1>x2) return 1; else return -1; } return 0; } }); Tree root=trees[0]; for(int i=1;i<trees.length;i++){ connect_Tree(root,trees[i]); }
ArrayList<Integer> list = new ArrayList<>(); preOrder(root,list); for (int i = 0; i < list.size(); i++) { answer[0][i]=list.get(i); } System.out.println(); list.clear(); postOrder(root,list); for(int i=0;i<list.size();i++){ answer[1][i]=list.get(i); }
return answer; } public static void connect_Tree(Tree root,Tree node){ if(root.x>node.x){ if(root.left!=null){ connect_Tree(root.left,node); }else{ root.left=node; } }else{ if (root.right != null) { connect_Tree(root.right,node); }else{ root.right=node; } } }
public void preOrder(Tree root, ArrayList<Integer> list) { list.add(root.index); if (root.left != null) { preOrder(root.left,list); } if (root.right != null) { preOrder(root.right,list); } }
public void postOrder(Tree root, ArrayList<Integer> list) { if (root.left != null) { postOrder(root.left,list); } if (root.right != null) { postOrder(root.right,list); } list.add(root.index); } } |
cs |
트리 구조를 만들어주면 끝난다.
그걸 생각못하고 처음에 너무 돌아 갔따.... 정답률 보니 트리 까먹어서 생각못한 사람들이 많은 것 같다.
기초를 잊지말자!