Given a tree, your are supposed to the "list all" leaves in "the Order of the", "the" and "left" right. Input Specification:
Each input file contains one test case. For each case, the gives a positive integer NNN (≤10\le 10≤10) which be the total number of nodes in the tree- -and hence the nodes are numbered from 0 to n−1n-1n−1. Then NNN 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" is put on the position. Any pair of the children are separated by a. Output Specification:
For each test case, print in one line all the leaves ' indices ' "in the" Order of "top down" and "left" right. There must be exactly one spaces between any adjacent numbers, and no extra spaces at the ' end of the ' line. Sample Input:
8 1---
0-
2 7---
5-
4 6
Sample Output:
4 1 5
This problem and the same, is also the use of array structure as the carrier, the storage node information. Finally, the output leaf nodes are traversed by the sequence of sequences.
For the sequence output, suppose the following tree structure
You need to build a queue, first add the root node to the queue, and then join the two subnodes each time a queue is queued, until the entire team column is empty, then the loop ends. Process is as follows
Import Java.util.Arrays;
Import java.util.LinkedList;
Import Java.util.Queue;
Import Java.util.Scanner;
Class treenode{int val;
int left;
int right;
public class Main {private static treenode[] TreeNode = new TREENODE[15];
private static int[] check = new INT[15]; public static void Main (string[] args) {//TODO auto-generated method stub Scanner scan = new Scanner (Sys
tem.in);
int T = Scan.nextint ();
Arrays.fill (check, 0);
for (int i=0;i<t;i++) {//System.out.println (treenode.length);
Treenode[i] = new TreeNode ();
Treenode[i].val = i;
String left = Scan.next ();
String right = Scan.next ();
if (Left.equals ("-")) {treenode[i].left =-1;
}else{treenode[i].left = Integer.parseint (left);
Check[integer.parseint (left)] = 1;
} if (Right.equals ("-")) { Treenode[i].right =-1;
}else{treenode[i].right = Integer.parseint (right);
Check[integer.parseint (right)] = 1;
} TreeNode root = null;
for (int i=0;i<t;i++) {if (check[i]==0) {root = Treenode[i];
} queue<treenode> list = new linkedlist<treenode> ();
List.add (root);
String an = "";
while (List.size ()!=0) {TreeNode node = List.poll ();
if (node.left!=-1) {List.add (treenode[node.left]);
} if (Node.right!=-1) {List.add (treenode[node.right]);
} if (Node.right==-1&&node.left==-1) {an + = node.val+ "";
} System.out.println (An.trim ()); }
}
The writer : Dream lei @ Mailbox
copyright Notice unless noted, this article Yu Menglei original compilation
Reprint Please indicate the source: http://zhiml.cn/index.php/post/38.html