7-1 列出叶结点 (25 分)
本文最后更新于1488天前,其中的信息可能已经有所发展或是发生改变。

对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。

输入格式:

首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 “-“。编号间以 1 个空格分隔。

输出格式:

在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

输出样例:

4 1 5

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <map>
#include <stack>
#include <string>
#include <queue>
#include <set>
#include <list>
using namespace std;
struct node {
    char left, right;
} nd[15];
vector <int> leaf[15];
void fun(int s, int cur) {
    if (nd[s].left == '-' && nd[s].right == '-') {
        leaf[cur].push_back(s);
        return ;
    }
    if (nd[s].left != '-') fun(nd[s].left - '0', cur + 1);
    if (nd[s].right != '-') fun(nd[s].right - '0', cur + 1);
}
int main() {
    int n, root[10], rt = 0;
    memset(root, 0, sizeof root);
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> nd[i].left >> nd[i].right;
        root[nd[i].left - '0'] = root[nd[i].right - '0'] = 1;
    }
    for (int i = 0; i < n; i++)
        if (!root[i]) {
            rt = i;
            break;
        }
    fun(rt, 1);
    bool f = false;
    for (int i = 1; i <= 10; i++) {
        for (int j = 0; j < leaf[i].size(); j++) {
            if (f) cout << " ";
            else f = true;
            cout << leaf[i][j];
        }
    }
    cout << endl;
}

 

点击数:787

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇