List Leaves(java实现)

7-4 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 N1. 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
思路:

1、用静态链表建立树。element记录节点在数组中的位置。

2、采用Queue队列实现树的层序遍历,直到Queue.isempty( ),入列add,出列poll.

3、设置flag,记录是第几个输出,用来控制什么时候输出空格。



import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;


public class Main {

	public static int n1;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		
		Jiedian [] jd = read(in);            //读入数据,建立tree
		print(jd);                           //用队列queue来实现树的层序遍历
	}

	private static void print(Jiedian[] jd) {
		// TODO Auto-generated method stub
		int flag=0;
		Queue<Jiedian> queue = new LinkedList<Jiedian>();
		queue.add(jd[n1]);
		while(!queue.isEmpty()) {
			Jiedian temp =queue.poll();
			if(temp.left==-1&&temp.right==-1) {
				if(flag==0)
					{
						System.out.print(temp.element);
						flag++;
					}
				else
					System.out.print(" "+temp.element);	
			}
			
			if(temp.left!=-1)
				queue.add(jd[temp.left]);
			if(temp.right!=-1)
				queue.add(jd[temp.right]);
		}
	}

	private static Jiedian[] read(Scanner in) {
		// TODO Auto-generated method stub
		int n = in.nextInt();
		Jiedian[ ] jd = new Jiedian[n];
		int [] check= new int[n];
		for(int i=0;i<n;i++) {
			check[i]=-1;
		}
		
		
		for(int i=0;i<n;i++) {
			Jiedian temp = new Jiedian();
			jd[i]=temp;
			String str;
			
			jd[i].element=i;
			
			str=in.next();
			if(str.equals("-"))
				jd[i].left=-1;
			else
			{
				jd[i].left=Integer.parseInt(str);
				check[jd[i].left]=jd[i].left;
			}
			
			
			str = in.next();
			if(str.equals("-"))
				jd[i].right=-1;
			else
			{
				jd[i].right=Integer.parseInt(str);
				check[jd[i].right]=jd[i].right;
			}			
		}
////////////////////找头结点/////////////////
		for(int i=0;i<n;i++) {
			if (check[i]==-1) {
				n1=i;
				break;
			}		
		}
////////////////////////////////////////////
		return jd;
	}

}

class Jiedian{
	
	int element;
	int left;
	int right;
	
}

猜你喜欢

转载自blog.csdn.net/weixin_38902950/article/details/80708678
今日推荐