從上往下打印二叉樹
題目描述:java
1 import java.util.Scanner; 2 3 public class Main { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Scanner in = new Scanner(System.in) ; 8 int node[][] = new int [1005][4] ; ///0爲節點的值,1左孩子,2父節點,3右孩子 9 while(in.hasNextInt()){ 10 int n = in.nextInt() ; 11 for(int i=1;i<=n;i++){ 12 node[i][0] = in.nextInt() ; 13 } 14 for(int i=1;i<=n;i++){ ///節點的初始化 15 node[i][2] = i ; 16 node[i][1]=node[i][3]=0 ; 17 } 18 for(int i=1;i<=n;i++){ 19 String str = in.next() ; 20 if(str.equals("d")){ 21 int x = in.nextInt() ; 22 int y = in.nextInt() ; 23 node[i][1] = x ; 24 node[i][3] = y ; 25 node[x][2] = i ; 26 node[y][2] = i ; 27 }else if(str.equals("l")){ 28 int x = in.nextInt() ; 29 node[i][1] = x ; 30 node[i][3] = 0 ; 31 node[x][2] = i ; 32 }else if(str.equals("r")){ 33 int x = in.nextInt() ; 34 node[i][1] = 0 ; 35 node[i][3] = x ; 36 node[x][2] = i ; 37 } 38 } 39 int root = 1 ; ///尋找根節點 40 while(root != node[root][2] ){ 41 root = node[root][2] ; 42 } 43 //System.out.println(root); 44 int arry1[] = new int[1005]; 45 int arry2[] = new int[1005]; 46 arry1[1] = root ; 47 int cnt = 2 ; 48 //System.out.println("yes"); 49 50 ///開始打印二叉樹 51 System.out.print(node[root][0]); 52 while(true){ 53 if(arry1[1]!=root){ ///再也不打印根節點 54 for(int i=1;i<cnt;i++){ 55 System.out.print(" "+node[arry1[i]][0]); 56 } 57 } 58 int c = 1 ; 59 for(int i=1;i<cnt;i++){ 60 if(node[arry1[i]][1]!=0){ ///若是有左孩子 61 arry2[c]=node[arry1[i]][1] ; 62 c++ ; 63 } 64 if(node[arry1[i]][3]!=0){ ///若是有右孩子 65 arry2[c]=node[arry1[i]][3] ; 66 c++ ; 67 } 68 } 69 cnt=c ; 70 for(int i=1;i<cnt;i++){ 71 arry1[i] = arry2[i] ; 72 } 73 if(c==1)break ; 74 } 75 } 76 } 77 }