【第五章】学习小结

本章我们学习了数据结构的一种——树。

相比于前面的内容来说,树的构造更为抽象、难懂,也是我们所接触的第一种非线性数据结构。

**前序遍历

void PreOrderTravel(node t[], int x)
{
    cout << t[x].name << " ";
    if(t[x].lch!=-1) PreOrderTravel(t, t[x].lch);
    if(t[x].rch!=-1) PreOrderTravel(t, t[x].rch);
}

中序遍历

void InOrderTravel(node t[], int x)
{
    if(t[x].lch!=-1) InOrderTravel(t, t[x].lch);
    cout << t[x].name << " ";
    if(t[x].rch!=-1) InOrderTravel(t, t[x].rch);
}

后序遍历

void PostOrderTravel(node t[], int x)
{
    if(t[x].lch!=-1) PostOrderTravel(t, t[x].lch);
    if(t[x].rch!=-1) PostOrderTravel(t, t[x].rch);
    cout << t[x].name << " ";
}

本章的例题要求掌握树的运用。

给定一棵树,你应该按照从上到下,从左到右的顺序列出所有的叶子。

每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数n(≤10),它是树中节

点的总数,因此节点的编号从0到n−1。接下来是n行,每行对应一个节点,并给出节点左、右子

级的索引。如果该子项不存在,则将在该位置放置一个“-”。任何一对孩子都被一个空间隔开。

对于每个测试用例,按从上到下和从左到右的顺序在一行中打印所有叶的索引。任何相邻的数字之

间必须正好有一个空格,并且行尾没有多余的空格。

本题对于给定的一个树结构,要求输出其叶子结点的序号。

#include "pch.h"
#include <iostream>
#include <queue>
using namespace std;
typedef struct {
    int lch;
    int rch;
}TrNode;
int buildtree(TrNode T[], int n);
void output(TrNode T[],int x,int n);
int main()
{
    TrNode ch[10];
    int x, n;
    cin >> n;
    x = buildtree(ch,n);
    output(ch, x, n);
    return 0;
}
int buildtree(TrNode T[], int n)
{
    bool check[10] = { false };
    char x, y;
    for (int i = 0; i < n; i++)
    {
        cin >> x >> y;
        if (x != '-') {
            T[i].lch = x-'0';
            check[T[i].lch] = true;
        }
        else T[i].lch = -1;

        if (y != '-')
        {
            T[i].rch = y-'0';
            check[T[i].rch] = true;
        }
        else T[i].rch = -1;
    
    }
    for (int i = 0; i < n; i++) {
        if (!check[i]) return i;
    }

}
void output(TrNode T[], int x,int n)
{
    int tmp;
    queue<int> q;
    q.push(x);
    int flag = 0;
    while (!q.empty()) {
        tmp = q.front();
        q.pop();
        if (tmp != -1) {
            q.push(T[tmp].lch);
            q.push(T[tmp].rch);
            if (T[tmp].lch == -1 && T[tmp].rch == -1) {
                if (flag != 0) cout << " ";
                flag = 1;
                cout << tmp;
            }
            
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/kirigirikyoko/p/10810527.html