码迷,mamicode.com
首页 > 其他好文 > 详细

List Leaves (25)

时间:2015-06-05 22:35:23      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

要按从上到下,从左到右的顺序查找叶子节点,可以采用广度优先搜索的办法

#include <iostream>
#include <queue>
using namespace std;
typedef struct{
    int loc;
    int left;
    int right;
}unit;
int n;
unit* a;
int father(int);
void printLeaf(int);
int main()
{
    cin >> n;
    getchar();
    a = (unit*)malloc(n*sizeof(unit));
    for (int i = 0; i < n; i++){
        a[i].loc = i;
        a[i].left = a[i].right = -1;
    }
    for (int i = 0; i < n; i++){
        char left=getchar();
        getchar();
        char right = getchar();
        getchar();
        if (0 <= left && left <= 9){
            a[i].left = left - 0;
        }
        if (0 <= right&&right <= 9){
            a[i].right = right - 0;
        }
    }
    int root = father(0);


    printLeaf(root);

    cin >> n;
}
int father(int son)
{
    for (int i = 0; i < n; i++){
        if (son == a[i].left || son == a[i].right){
            son = i;
            i = 0;
        }
    }
    return son;
}
void printLeaf(int root)
{
    queue<unit> q;
    queue<int> print;

    q.push(a[root]);
    while (q.empty() != true){
        if (q.front().left == -1 && q.front().right == -1){
            print.push(q.front().loc);
            q.pop();
            continue;
        }
        if (q.front().left != -1){
            q.push(a[q.front().left]);
        }
        if (q.front().right != -1){
            q.push(a[q.front().right]);
        }
        q.pop();
    }
    while (print.size() >= 2){
        cout << print.front() << " ";
        print.pop();
    }
    cout << print.front();
}

 

List Leaves (25)

标签:

原文地址:http://www.cnblogs.com/zhouyiji/p/4555585.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!