您的位置:首页 > 其它

03-树1. List Leaves (25)

2015-04-06 12:14 429 查看
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
;

char data[][] = new char
[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];

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: