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


题目要求

给出一个二叉树,你需要按从上到下,从左到右的顺序输出所有的叶结点。

输入要求

  • 第一行输出树的总结点N,并且0<=N<=10
  • 结点从0-N-1进行标记
  • 有N行,每行对应一个结点,给出结点的左右儿子,之间用一个空格隔开
  • 如果儿子不存在,则用“-”表示

输出要求

在一行中按从上到下,从左到右的顺序列出所有的叶结点,结点之间用一个空格隔开,在行的尾部没有多余的空格。


用c++编的代码如下:

#include 
#include 
#include 

using namespace std;

#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1

queue<int> q;

struct TreeNode
{
    ElementType Element;
    Tree Left;
    Tree Right;
}T1[MaxTree];
int BuildTree(struct TreeNode T[]);
void FineLeaves(Tree R);

int main()
{
    Tree R;
    R = BuildTree(T1);
    FineLeaves(R);
    return 0;
}

\\创建二叉树 
int BuildTree(struct TreeNode T[])
{
    int N,i;
    scanf("%d\n",&N);
    char cl,cr;
    Tree check[MaxTree],Root = Null;
    if(N)
    {
        for (i=0;i0;
        }
        for(i=0;iscanf("%c %c\n",&cl,&cr);
            if(cl != '-')
            {
                T[i].Left = cl-'0';
                check[T[i].Left] = 1;
            }
            else
                T[i].Left = Null;
            if(cr != '-')
            {
                T[i].Right = cr-'0';
                check[T[i].Right] = 1;
            }
            else
                T[i].Right = Null;
        }
        for(i=0;iif(!check[i])
            {
                Root = i;
                break;
            }

        }
    }
    return Root;
}

\\找出二叉树的叶结点 
void FineLeaves(Tree R)
{
    int flag = 0;
    if(R == Null)
        return;
    q.push(R);
    int temp = 0;
    while(!q.empty())
    {
       temp = q.front();
       if((T1[temp].Left == Null) &&(T1[temp].Right == Null))
       {
           if(!flag)
           {
               flag = 1;
           }
           else
               printf(" ");
           printf("%d",temp);

       }
       if(T1[temp].Left != Null)
            q.push(T1[temp].Left);
        if(T1[temp].Right != Null)
            q.push(T1[temp].Right);
        q.pop();

    }

}

结论:本来打算是用c写的,但发现c中没有queue的库,没办法采用C++写,本人对C++并不是很熟悉,所以写的有点粗糙,有问题的地方,欢迎指正。

你可能感兴趣的:(二叉树,叶结点遍历,二叉树,叶结点)