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
题解
第一次
思路
- 输入,并且建树nodeList(抽象的,实际上是在父节点里保存子节点在数组里的id)
- BST的中序序列是非递减的,中序遍历这颗树,得到中序遍历的序号序列inOrderIndexList,非递减排序给定的数组valueList,这样valueList[i]在给定形态的数中的位置就会是inOrderIndexList[i],在nodeList里按照这个关系逐个给节点插入数值
- 用queue层序遍历,遍历序列保存在ans里
- 输出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每一天**