03-树2 List Leaves (25分)

来源:互联网 发布:ubuntu anaconda 编辑:程序博客网 时间:2024/05/17 04:41

层序遍历

题意:

  找到叶子节点 从上到下 从左到右 输出叶子节点

思路:

  用一个队列来模拟

坑点:

  最后输出格式要注意 最后一个没有空格

#include<cstdio>#include<queue>using namespace std;#define MaxTree 10#define ElementType char#define Tree int#define Null -1queue<int> q;struct TreeNode{    ElementType Element;    Tree Left;    Tree Right;}T1[MaxTree];Tree BuildTree(struct TreeNode T[]){    Tree Root = -1;    int N;    int check[10];    char cl,cr;    scanf("%d\n", &N);    //printf("N=%d\n", N);    int i = 0;    if(N){        for(i = 0; i < N; ++i) check[i] = 0;        for(i = 0; i < N; ++i){            scanf("%c %c\n", &cl, &cr);            T[i].Element = i;            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 ; i < N; ++i){            if(!check[i]) break;        }        Root = i;    }    //printf("Root=%d\n", Root);    //for(i = 0; i < N; ++i)       // printf("element=%d left=%d right=%d\n", T1[i].Element, T1[i].Left, T1[i].Right);    return Root;}void findLeaf(Tree R){    int flag = 1;    if(R == Null)        return ;    q.push(R);    int temp = 0;    while(!q.empty()){        //printf("no empty\n");        temp = q.front();        if((T1[temp].Left == Null) && (T1[temp].Right == Null)){            if(flag){                printf("%d", temp);                flag = 0;            }            else                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();    }}int main(){    Tree R1;    R1 = BuildTree(T1);    findLeaf(R1);    return 0;}
0 0
原创粉丝点击