Given a tree, you is supposed to list all the leaves in the order of the top down, and left to right.
Input Specification:
Each input file contains the one test case. For each case, the first line gives a positive integerNn(\le 10< Span class= "Mrel" >≤10) which is the total number of nodes in the tree --and hence the nodes is numbered from 0 to n?1. Then nn 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 "-" 'll be put on the position. Any pair of children is separated by a space.
Output Specification:
For each test case, print in one line all the leaves ' indices in the order of the top down, and left to right. There must is exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:
81 -- -0 -2 7- -- -5 -4 6
Sample Output:
4 1 5
解决思路:
1.用静态链表来存储节点,若孩子为“-”,则标记为-1.返回root在数组中的位置。
2.因为题目要求从上到下,从左到又,这需要按层遍历的方法,因此用数组来创建一个队列。
3.先在队列中输入根节点,开启循环。输出根节点,判断节点左右孩子是否为-1,若真,打印根节点,若不是,判断左孩子是否为-1,若不是,左孩子入队,同样的操作右孩子。依次循环
ImportJava.util.Scanner;classNode//Create a node type{ intkey; intLeft ; intRight ; }classQueue//Create a queue type{ intFront; intRear; intnum; intmaxsize; int[] ARRQ; PublicQueueintN//Initialize Queue{maxsize=N; Front=0; Rear=-1; Num=0; Arrq=New int[maxsize]; } Public voidInsertintvalue) { if(rear==maxsize-1) { Throw NewRuntimeException ("full"); } Else{Rear=rear+1; Arrq[rear]=value; Num++; } } Public intRemove () {inttemp=Arrq[front]; Arrq[front]=0; Front++; if(front==maxsize) {Front=0; } num--; returntemp; } Public BooleanIsEmpty () {returnNum==0; }}classTest//Main type{ Public Static voidMain (string[] args) {Scanner sc=NewScanner (system.in); Node[] Arr=NewNode[8]; intHead=Biuldtree (ARR,SC); Listleaves (Arr,head); } Public Static intBiuldtree (node[] Arr,scanner SC) {intn=Sc.nextint (); String Templeft; String Tempright; int[] flag=New int[N]; intRoot=0; for(intI=0;i<n; i++) {node node=NewNode (); Templeft=Sc.next (); Tempright=Sc.next (); Arr[i]=node; if(Templeft.equals ("-") ) {Node.left=-1; } Else{node.left=Integer.parseint (Templeft); Flag[node.left]=1; } if(Tempright.equals ("-") ) {Node.right=-1; } Else{node.right=Integer.parseint (tempright); Flag[node.right]=1; } } for(intI=0;i<n; i++ ) { if(flag[i]==0) {root=i; } } returnRoot; } Public Static voidListleaves (node[] arr,inthead) {Queue Arrq=NewQueue (8); Arrq.insert (head); intA=0; while(!Arrq.isempty ()) {Head=Arrq.remove (); if(Arr[head].left==-1&&arr[head].right==-1) { if(a==0) {System.out.print (head); } ElseSystem.out.print (" "+head); A++; } if(Arr[head].left!=-1) {Arrq.insert (arr[head].left); } if(Arr[head].right!=-1) {Arrq.insert (arr[head].right); } } }}
Print results
Listleaves problem Java description