PTA 03-树2 List Leaves(数组模拟链式存储+层序遍历叶子节点)

大体思路:

1.选取数据结构,输入的是每个0到N-1节点的左右孩子情况,考虑数组模拟链式存储,然后根据度数找出根(度数为零)。

代码:

struct treeNode//数组模拟链式存储
{
    int left, right;
}d[1005];
    cin>>n;
    //读入
    for(int i=0;i<n;++i) {
        cin>>a>>b;
        d[i].left=isdigit(a)?a-'0':-1;
        if(isdigit(a)) degree[a-'0']++;
        d[i].right=isdigit(b)?b-'0':-1;
        if(isdigit(b)) degree[b-'0']++;
    }    
    //取根
    int root=-1;
    for(int i=0;i<n;++i)
        if(!degree[i]) {root=i;break;}

2.层序遍历,队列辅助。从根节点开始,节点入队,访问该节点的左右孩子,若有则入队,如此循环,直到队列为空。

代码:

void levelTraverse(int root)//层序遍历,队列辅助
{
    queue<int> q;
    if(root==-1) return;//空树
    q.push(root);//存储根节点
    while(!q.empty()){
        root=q.front();q.pop();
        if(d[root].left==-1&&d[root].right==-1) ans.push_back(root);//输出叶子节点(leaf indice)
        //访问根节点的左右孩子
        if(d[root].left!=-1) q.push(d[root].left);
        if(d[root].right!=-1) q.push(d[root].right);
    }
}

另外,本体是输出叶子节点,判一下左右儿子情况,记录在一个vector里,最后依次输出即可。

代码:

#include <bits/stdc++.h>
using namespace std;

int n, degree[1005];//degree数组记录每个节点的度
char a, b;
struct treeNode//数组模拟链式存储
{
    int left, right;
}d[1005];
vector<int> ans;

void levelTraverse(int root)//层序遍历,队列辅助
{
    queue<int> q;
    if(root==-1) return;//空树
    q.push(root);//存储根节点
    while(!q.empty()){
        root=q.front();q.pop();
        if(d[root].left==-1&&d[root].right==-1) ans.push_back(root);//输出叶子节点(leaf indice)
        //访问根节点的左右孩子
        if(d[root].left!=-1) q.push(d[root].left);
        if(d[root].right!=-1) q.push(d[root].right);
    }
}
int main()
{
    cin>>n;
    //读入
    for(int i=0;i<n;++i) {
        cin>>a>>b;
        d[i].left=isdigit(a)?a-'0':-1;
        if(isdigit(a)) degree[a-'0']++;
        d[i].right=isdigit(b)?b-'0':-1;
        if(isdigit(b)) degree[b-'0']++;
    }
    //取根
    int root=-1;
    for(int i=0;i<n;++i)
        if(!degree[i]) {root=i;break;}
    //层序遍历
    levelTraverse(root);
    //输出叶子节点
    int len=ans.size();
    for(int i=0;i<len;++i)
        printf("%d%c",ans[i]," \n"[i==len-1]);
    return 0;
}
/*
8
0 1 -
1 - -
2 0 -
3 2 7
4 - -
5 - -
6 5 -
7 4 6
*/

猜你喜欢

转载自www.cnblogs.com/ChenyangXu/p/10741660.html