7-8 浪漫侧影(25分)建树+新解题思路

浪漫侧影 (25 分)

在这里插入图片描述

题目描述

“侧影”就是从左侧或者右侧去观察物体所看到的内容。例如上图中男生的侧影是从他右侧看过去的样子,叫“右视图”;女生的侧影是从她左侧看过去的样子,叫“左视图”。
我们将二叉树的“侧影”定义为从一侧能看到的所有结点从上到下形成的序列。例如下图这棵二叉树,其右视图就是 { 1, 2, 3, 4, 5 },左视图就是 { 1, 6, 7, 8, 5 }。
在这里插入图片描述

于是让我们首先通过一棵二叉树的中序遍历序列和后序遍历序列构建出一棵树,然后你要输出这棵树的左视图和右视图。

输入格式:

输入第一行给出一个正整数 N (≤20),为树中的结点个数。随后在两行中先后给出树的中序遍历和后序遍历序列。树中所有键值都不相同,其数值大小无关紧要,都不超过 int 的范围。

输出格式:

第一行输出右视图,第二行输出左视图,格式如样例所示。

输入样例:
8
6 8 7 4 5 1 3 2
8 5 4 7 6 3 2 1
输出样例:
R: 1 2 3 4 5
L: 1 6 7 8 5

分析

1)建树直接根据模板写,然后得到tree数组。
2)输出右侧面就是从index=1开始,如果index×2+1存在结点就输出,不存在则查看index×2,若存在就输出,都不存在就从index×2开始,往寻找到第一个结点即为最右的结点。
3)输出左侧面与右侧面类似,如果index×2存在结点就输出,不存在则查看index×2+1,若存在就输出,都不存在就从index×2开始,往寻找到第一个结点即为最左的结点。

代码
#include <iostream>
#include <algorithm>
#include <cmath>

#define MAX 100000

using namespace std;

int n, midord[30], postord[30], tree[MAX], level = 0;

void createTree (int *postord, int *midord, int n, int index) {
    if (!n) return ;
    int k = 0;
    while (postord[n - 1] != midord[k]) k ++;
    tree[index] = midord[k];
    level = max(level, index);
    
    createTree(postord, midord, k, index * 2);
    createTree(postord + k, midord + k + 1, n - k - 1, index * 2 + 1);
}

int main () {
    cin >> n;
    
    for (int i = 0; i < n; i ++) cin >> midord[i];
    for (int i = 0; i < n; i ++) cin >> postord[i];
    
    createTree(postord, midord, n, 1);
    
    for (int i = 1; i <= 22; i ++)
        if (level < pow(2, i)) {
            level = i;
            break;
        }
    
    cout << "R: ";
    int cnt = 0, idx = 1;
    while (cnt < level) {
        if (tree[idx]) cout << tree[idx];
        
        if (tree[idx * 2 + 1]) idx = idx * 2 + 1;
        else if (tree[idx * 2]) idx = idx * 2;
        else {
            idx = idx * 2;
            while (!tree[idx]) idx --;
        }
        
        cnt ++;
        if (cnt != level) cout << ' ';
        else cout << endl;
    }
    
    cout << "L: ";
    cnt = 0, idx = 1;
    while (cnt < level) {
        if (tree[idx]) cout << tree[idx];
        
        if (tree[idx * 2]) idx = idx * 2;
        else if (tree[idx * 2 + 1]) idx = idx * 2 + 1;
        else {
            idx = idx * 2;
            while (!tree[idx]) idx ++;
        }
        
        cnt ++;
        if (cnt != level) cout << ' ';
        else cout << endl;
    }
    
    return 0;
}
  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值