1020 Tree Traversals (25分)(二叉树的遍历)

二叉树的遍历是以DFS和BFS为基础的,无非是在DFS和BFS上面的变形,熟练掌握了BFS和DFS以后,这种类型的题目也就没有什么太大的难度了

题目描述如下:

在这里插入图片描述
题目大致意思:
给出二叉树的后续遍历序列和中序遍历序列,重建二叉树后,输出二叉树的层序遍历序列。
大致思路:
用两个数组分别来存储树的后序遍历和中序遍历序列,使用递归的方法来从新构建一棵树,构建成功后,对该树使用队列进行广度优先遍历即可。
提交结果如下:
在这里插入图片描述
注意:
在构建二叉树时,存在一个坑,一定要先计算出左子树的长度后,再进行递归,因为在存储后序遍历和中序遍历的数组中,经过几次递归之后,中序遍历的第一个元素的位置与后序遍历的第一个元素的位置已经不同了,仅靠下标是无法划分左右子树的,只能通过确定左子树的长度,进而对数组进行划分。
提交的代码如下:

#include<iostream>
#include<queue>
using namespace std;
int post_order[30];
int in_order[30];
int n;
struct Node
{
    int data;
    Node* lchild, * rchild;
};
Node* creat_tree(int high_post, int low_post, int low_in, int high_in);
int main()
{
    cin >> n;
    for (int i = 0;i < n;i++)
        cin >> post_order[i];
    for (int i = 0;i < n;i++)
        cin >> in_order[i];
    Node* root = creat_tree(n - 1, 0, 0, n - 1);
    queue<Node*> que;
    que.push(root);
    int index=0;
    while (!que.empty())
    {
        Node* top = que.front();
        index++;
        if(index<n)
            cout << top->data << " ";
        else
            cout<<top->data<<endl;
        que.pop();
        if (top->lchild != NULL)
            que.push(top->lchild);
        if (top->rchild != NULL)
            que.push(top->rchild);
    }
}
Node* creat_tree(int high_post, int low_post, int low_in, int high_in)

{
    if (low_in > high_in || high_post < low_post)
        return NULL;
    Node* root = new Node;
    root->data = post_order[high_post];
    int temp = post_order[high_post];
    int ans=0;
    for (int i = low_in;i <= high_in;i++)
    {
        if (temp == in_order[i])
        {
            ans = i;
            break;
        }
    }
    int numleft = ans - low_in;//求出左子树的长度
    root->lchild = creat_tree(low_post+numleft-1, low_post, low_in, ans - 1);
    root->rchild = creat_tree(high_post - 1, low_post+numleft, ans + 1, high_in);
    return root;
}

本次提交后,累计得分为1544。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值