(2016秋数据结构课后练习题总结)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 NNN (≤10\le 1010) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1N-1N1.  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 "-" 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

这道题和上一体一样,也是利用数组结构为载体,存储结点的信息。最后在利用层序遍历输出叶节点。

关于层序输出,假设有以下树结构


需要先构建一个队列,先向队列中添加根节点,之后每次每个队列一出队,就加入其两个子节点,直到整个队列为空,则循环结束。过程如下


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(System.in);
        int T = scan.nextInt();
        Arrays.fill(check, 0);
        for(int i=0;i list = new LinkedList();
        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());
    }
}

本文作者 : 梦磊 @ 邮箱

版权声明 除非注明,本文由 梦磊 原创编译

转载请注明出处: http://zhiml.cn/index.php/post/38.html


你可能感兴趣的:(数据结构)