1099 Build A Binary Search Tree (30分)[BST][层序遍历]

By Jalan

知识工具需求

数学

数据结构和算法

  • BST
  • 层序遍历

题干

给一个树的结构和一串数字,保证这串数字可以以唯一的形态组成给定结构的BST,要求输出这个BST的层序遍历.

例子

例1

输入
9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42
输出
58 25 82 11 38 67 45 73 42

题解

第一次

思路

  1. 输入,并且建树nodeList(抽象的,实际上是在父节点里保存子节点在数组里的id)
  2. BST的中序序列是非递减的,中序遍历这颗树,得到中序遍历的序号序列inOrderIndexList,非递减排序给定的数组valueList,这样valueList[i]在给定形态的数中的位置就会是inOrderIndexList[i],在nodeList里按照这个关系逐个给节点插入数值
  3. 用queue层序遍历,遍历序列保存在ans里
  4. 输出ans

编写用时

20分钟

代码

CPP
#include <algorithm>
#include <bits/stdc++.h>
#include <stdio.h>
#include <vector>
using namespace std;
int n;
typedef struct node
{
    int index;
    int v;
    int l;
    int r;
} node;
vector<node> nodeList;
vector<int> valueList;
vector<int> inOrderIndexList;

void DFSIN(int i)
{
    if (nodeList[i].l != -1)
    {
        DFSIN(nodeList[i].l);
    }
    inOrderIndexList.push_back(nodeList[i].index);
    if (nodeList[i].r != -1)
    {
        DFSIN(nodeList[i].r);
    }
}
int main(int argc, char const *argv[])
{
    //1
    cin >> n;
    nodeList.resize(n);
    valueList.resize(n);
    for (int i = 0; i < n; i++)
    {
        int l, r;
        scanf("%d %d", &l, &r);
        nodeList[i].index = i;
        nodeList[i].l = l;
        nodeList[i].r = r;
    }
    for (int i = 0; i < n; i++)
    {
        int temp;
        scanf("%d", &temp);
        valueList[i] = temp;
    }
    //2
    sort(valueList.begin(), valueList.end());
    DFSIN(0);
    for (int i = 0; i < n; i++)
    {
        nodeList[inOrderIndexList[i]].v = valueList[i];
    }
    //3
    vector<int> ans;
    queue<int> q;
    q.push(0);
    while (q.size() != 0)
    {
        int now = q.front();
        q.pop();
        ans.push_back(nodeList[now].v);
        if (nodeList[now].l != -1)
        {
            q.push(nodeList[now].l);
        }
        if (nodeList[now].r != -1)
        {
            q.push(nodeList[now].r);
        }
    }
    //4
    for (int i = 0; i < ans.size(); i++)
    {
        printf("%d", ans[i]);
        if (i != (int)ans.size() - 1)
        {
            printf(" ");
        }
    }

    return 0;
}

运行用时

在这里插入图片描述

结尾

看在我写了这么多注释的份上可以给我点个赞嘛,求求惹=]砰砰砰,给我加点写下去的油呀
@.@
也欢迎关注我的CSDN账号呀=]

                                        **开心code每一天**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值