您的位置:首页 > 其它

题目1523:从上往下打印二叉树

2016-01-14 14:27 323 查看
题目描述:

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

输入:

输入可能包含多个测试样例,输入以EOF结束。

对于每个测试案例,输入的第一行一个整数n(1<=n<=1000, :n代表将要输入的二叉树元素的个数(节点从1开始编号)。接下来一行有n个数字,代表第i个二叉树节点的元素的值。接下来有n行,每行有一个字母Ci。

Ci=’d’表示第i个节点有两子孩子,紧接着是左孩子编号和右孩子编号。

Ci=’l’表示第i个节点有一个左孩子,紧接着是左孩子的编号。

Ci=’r’表示第i个节点有一个右孩子,紧接着是右孩子的编号。

Ci=’z’表示第i个节点没有子孩子。

输出:

对应每个测试案例,

按照从上之下,从左至右打印出二叉树节点的值。

样例输入:

7

8 6 5 7 10 9 11

d 2 5

d 3 4

z

z

d 6 7

z

z

样例输出:

8 6 10 5 7 9 11

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Main {

public static void main(String[] args) throws IOException {

PrintWriter cout = new PrintWriter(System.out)  ;

while(Cin.hashNext()){
new Task().solve(Cin.Int() , cout) ;
}
cout.flush() ;
}

}

class  Task{

Node[] node ;
int[]  id ;

void solve(int n , PrintWriter cout) throws IOException{
node = new Node[n+1] ;
id = new int[n+1] ;
for(int i = 1 ; i <= n ; i++){
id[i] = Cin.nextInt()  ;
node[i] = new Node() ;
}

int u , v ;

for(int i = 1 ; i <= n ; i++){
String s = Cin.nextString() ;
if(s.equals("d")){
u = Cin.nextInt() ;
v = Cin.nextInt() ;
node[i].left = u ;
node[i].right = v ;
node[u].father = node[v].father = i ;
}
else if(s.equals("l")){
u = Cin.nextInt() ;
node[i].left = u ;
node[u].father  = i ;
}
else if(s.equals("r")){
v = Cin.nextInt() ;
node[i].right = v ;
node[v].father = i ;
}
}

int root = -1 ;
for(int i = 1 ; i <= n ; i++){
if(node[i].father == -1) root = i ;
}

List<Integer> answer = new ArrayList<Integer>() ;
Queue<Integer> que = new  LinkedList<Integer>() ;
que.add(root) ;
while(! que.isEmpty()){
u = que.poll() ;
answer.add(u) ;
if(node[u].left != -1) que.add(node[u].left) ;
if(node[u].right != -1) que.add(node[u].right) ;
}
cout.print(id[answer.get(0)]) ;
for(int i = 1 ; i < answer.size() ; i++) cout.print(" " + id[answer.get(i)] ) ;
cout.println() ;

}

}

class  Node{
int father ;
int left , right ;
Node(){
father = -1 ;
left = right = -1 ;
}
}

class  Cin{
static StreamTokenizer cin = new StreamTokenizer(new BufferedInputStream(System.in)) ;

static boolean hashNext() throws IOException{
return  cin.nextToken() != cin.TT_EOF ;
}

static int nextInt() throws IOException{
cin.nextToken() ;
return (int)cin.nval ;
}

static int Int() throws IOException{
return (int)cin.nval ;
}

static String nextString() throws IOException{
cin.nextToken() ;
return (String)cin.sval ;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: