03-树2 List Leaves (25分)
Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each test case, print in one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5
思路分析:建立一棵树,每行代表一个结点,序号从0~N(N < 9 ),‘ - ’ 代表没有孩子。首先找到树的根,然后依次从根开始查找当前结点的左孩子和右孩子,并加入到队列中,每次循环队列出队一个结点,如果该结点都没有左右孩子,则输出。(BFS,即层序遍历的思想)。可以不用建立一棵树,直接用数组模拟,这样更方便一些。
package Test1216;
import java.util.Scanner;
class TreeNode{
int key;
int left;
int right;
}
class Queue {
int[] arr;
int front = 0;
int rear = -1;
int size;
int num = 0;
int tmp;
Queue(int size) {
this.size = size;
arr = new int[size];
}
public void add(int value) {
if (!isFull()) {
if (rear == size - 1)
rear = -1;
arr[++rear] = value;
num++;
} else
System.out.println("队列满,不能添加元素");
}
public int remove() {
if (!isEmpty()) {
num--;
if (front != size - 1) {
return arr[front++];
} else {
tmp = arr[front];
front = 0;
return tmp;
}
} else {
System.out.println("队列空,不能删除元素");
return -1;
}
}
public boolean isEmpty() {
if (num == 0)
return true;
return false;
}
public boolean isFull() {
if (num == size)
return true;
return false;
}
}
public class ListLeaves {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int tmp;
TreeNode[] node = new TreeNode[N];
int head = read(node, sc, N);
Queue queue=new Queue(N);
queue.add(head);
while(!queue.isEmpty()){
tmp=queue.remove();
if(node[tmp].left==-1 && node[tmp].right==-1)
System.out.print(tmp+" ");
if(node[tmp].left!=-1){
queue.add(node[tmp].left);
}
if(node[tmp].right!=-1){
queue.add(node[tmp].right);
}
}
}
public static int read(TreeNode[] node, Scanner sc, int N) {
String tmpLeft;
String tmpRight;
int root = -1;
int[] flag = new int[N];
for (int i = 0; i < N; i++) {
TreeNode tmpNode=new TreeNode();
tmpNode.key = i;
tmpLeft = sc.next();
tmpRight = sc.next();
node[i]=tmpNode;
if (tmpLeft.equals("-")) {
node[i].left = -1;
} else {
node[i].left = Integer.parseInt(tmpLeft);
flag[node[i].left] = 1;
}
if (tmpRight.equals("-")) {
node[i].right = -1;
} else {
node[i].right = Integer.parseInt(tmpRight);
flag[node[i].right] = 1;
}
}
for (int i = 0; i < N; i++) {
if (flag[i] == 0)
root = i;
}
return root;
}
}