1111. 二哥学二叉树

6 篇文章 0 订阅

Description

二哥学了二叉树的顺序存储后,被下面一个问题难住了,于是他请你帮他解决。给你一个前序遍历和中序遍历,问顺序存储的数组是什么样子的。

Example

Input Format

第一行为前序遍历,第二行为中序遍历,节点个数不超过26.

Output Format

输出一行,表示顺序存储的数组,以空格隔开,NULL表示空节点,数组空间不超过1000个节点.

Sample Input

ABCD
BADC

Sample Output

A B C NULL NULL D

C++实现如下:

#include <iostream>
#include <string>
 
using namespace std;
 
struct node
{
    char val;
    node *left;
    node* right;
    node() :val(0), left(nullptr), right(nullptr) {}
    node(char v)
            :val(v), left(nullptr), right(nullptr) {}
};
 
node* init(string s1, string s2)
{
    node *cur_root = new node(s1[0]);
    int num = 0;
    for (; num < s2.length(); num++)
        if (s1[0] == s2[num]) break;
    if (num > 0)
        cur_root->left = init(s1.substr(1, num), s2.substr(0, num));
    if (num < s2.length() - 1)
        cur_root->right = init(s1.substr(num + 1, s1.length() - num - 1), s2.substr(num + 1, s2.length() - num - 1));
    return cur_root;
}
 
void SaveTree(node *root, int *arr, int pos)
{
    arr[pos] = root->val - 'A' + 1;
    if (root->left != nullptr)
        SaveTree(root->left, arr, pos * 2);
    if (root->right != nullptr)
        SaveTree(root->right, arr, pos * 2 + 1);
}
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    string s1, s2;
    cin >> s1 >> s2;
    node *root = init(s1, s2);
    int arr[1005];
    for (int i = 0; i < 1005; i++) arr[i] = 0;
    SaveTree(root, arr, 1);
    int tail = 1004;
    for (; tail >= 0; tail--)
        if (arr[tail]) break;
    for (int i = 1; i <= tail; i++)
    {
        if (arr[i])
            cout << char(arr[i] - 1 + 'A') << " ";
        else
            cout << "NULL ";
    }
    cout << endl;
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值