A1099 Build A Binary Search Tree (30 分| 二叉查找树,附详细注释,逻辑分析)
其他
2020-03-28 11:25:07
阅读次数: 0
写在前面
- 思路分析
- 二叉搜索树 中序从小到大顺序输出
- 从小到大可以建立一个树
- 热点知识,学习ing
测试用例
ac代码
- 参考代码
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
struct Node
{
int data;
int left,right;
} root[105];
int digit[105],now = 0;
void Inorder(int x)
{
if(root[x].left != -1)
Inorder(root[x].left);
root[x].data = digit[now++];
if(root[x].right != -1)
Inorder(root[x].right);
}
int main()
{
int n,x,y;
scanf("%d",&n);
for(int i = 0; i < n ; i++ )
scanf("%d%d",&root[i].left,&root[i].right);
for(int i = 0 ; i < n; i++)
scanf("%d",&digit[i]);
sort(digit,digit+n);
Inorder(0);
queue<Node>qu;
qu.push(root[0]);
vector<int>vec;
while(qu.empty() == 0)
{
Node tmp = qu.front();
qu.pop();
vec.push_back(tmp.data);
if(tmp.left != -1)
qu.push(root[tmp.left]);
if(tmp.right != -1)
qu.push(root[tmp.right]);
}
for(int i = 0 ; i < n; i++)
printf("%d%c",vec[i]," \n"[i==n-1]);
return 0;
}
发布了328 篇原创文章 ·
获赞 107 ·
访问量 39万+
转载自blog.csdn.net/qq_24452475/article/details/100620156