1102 Invert a Binary Tree (25 分)——甲级:建树输出中序、层序(二叉树镜像输出)

本文介绍了一种解决二叉树镜像遍历问题的方法,通过结构体数组存储二叉树信息,利用检查数组确定根节点,最终实现层序和中序遍历的镜像输出。代码使用C++实现,详细展示了如何处理输入输出和遍历过程。

The following is from Max Howell @twitter:
在这里插入图片描述
Now it’s your turn to prove that YOU CAN invert a binary tree!

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node from 0 to N−1, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.

Output Specification:
For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:
在这里插入图片描述
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

题目大意:结点编号从0到n-1。对于每个结点,给出左右儿子存在情况以及索引,要求输出层序和中序的镜像。
思路:用结构体数组存二叉树,check数组标记有父亲节点的结点,最后没有被标记的就是根节点。利用根节点输出即可。

代码如下:

#include <iostream>
#include <queue>
using namespace std;
struct node
{
    int left;
    int right;//-1表示没有对应儿子结点
}a[10];
int n, check[10], cnt;
int build(int n)
{
    int i;
    for(i = 0; i < n; i++)
    {
        char lchild, rchild;
        cin >> lchild >> rchild;
        if(lchild == '-') a[i].left = -1;
        else
        {
            a[i].left = lchild-'0';
            check[lchild-'0'] = 1;
        }
        if(rchild == '-') a[i].right = -1;
        else
        {
            a[i].right = rchild-'0';
            check[rchild-'0'] = 1;
        }
    }
    for(i = 0; i < n; i++) if(!check[i]) return i;//没有被标记的即为根节点
}
void level_order(int t)
{
    queue<int>q;
    int flag = 0;
    q.push(t);
    while(!q.empty())
    {
        int x = q.front();
        if(!flag)
        {
            flag = 1;
            cout << x;
        }
        else cout << " " << x;
        if(a[x].right != -1) q.push(a[x].right);
        if(a[x].left != -1) q.push(a[x].left);//镜像:先右,后左
        q.pop();
    }
    cout << endl;
}
void in_order(int t)
{
    if(t == -1) return ;
    in_order(a[t].right);
    cnt++;
    if(cnt == n) cout << t << endl;
    else cout << t << " ";
    in_order(a[t].left);//镜像:右-根-左
}
int main()
{
    cin >> n;
    int head = build(n);
    level_order(head);
    in_order(head);
    return 0;
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值