03-树1. List Leaves (25)

来源:互联网 发布:amd显卡驱动linux 编辑:程序博客网 时间:2024/05/30 04:16
package a;

import java.sql.Struct;
import java.util.Collection;
import java.util.Queue;
import java.util.Scanner;
import javax.print.DocFlavor.INPUT_STREAM;
import java.util.*;


public class bb {
static public void main(String[] args){
Scanner input = new Scanner(System.in);
// node text[] = new node[2];
// text[0] = new node();
// text[0].i = 0;
int n = input.nextInt();
int array[] = new int [n];
char data[][] = new char [n][2];
for(int i = 0; i < n ; i++){
for(int j = 0; j < 2 ; j++){
data[i][j] = input.next().toCharArray()[0];
}
}
node root = tree(n,data);
show(root);

}
static public node tree(int a,char p[][]){
node np[] = new node[a];
for(int i=0; i<a; i++){
np[i] = new node();
np[i].i = i;
}
for(int i=0; i<a; i++){
// for(int j=0; j<2; j++){
// if(p[i][j] == '-'){
// np[i].child[j] = null;
// }
// else{
// np[i].child[j] = np[ (p[i][j] - '0' + 0)];
// }
// }
if(p[i][0] == '-')
np[i].child[0] = null;
else{
np[i].child[0] = np[ (p[i][0] - '0' + 0)];
np[i].child[0].father = np[i];
}
if(p[i][1] == '-')
np[i].child[1] = null;
else{
np[i].child[1] = np[ (p[i][1] - '0' + 0)];
np[i].child[1].father = np[i];
}
}
return findroot(np[0]);
}
static public node findroot(node a){
for(;a.father != null;){
a = a.father;
}
return a;
}
static public void show(node root){
Queue <node> data = new LinkedList <node> () ;
data.add(root);
for(;data.size() != 0;){
node father;
for(int i=0,s=data.size();i<s;i++){
father = data.poll();
if(isleaf(father)){
System.out.print(father.i);
if(data.isEmpty());
else
System.out.print(' ');
}
else{
if(father.child[0] != null){
data.add(father.child[0]);
}
if(father.child[1] != null){
data.add(father.child[1]);
}
}
}

}
}
static public boolean isleaf(node a){
if(a.child[0] == null && a.child[1] == null)
return true;
else
return false;
}


}
 class node{
int i;
node child[];
node father;
node(){
child = new node[2];
}
}
0 0
原创粉丝点击