zl程序教程

您现在的位置是:首页 >  其他

当前栏目

1099 Build A Binary Search Tree (30 分)【难度: 一般 / 知识点: 建立二叉搜索树】

搜索知识点 建立 30 Tree build search Binary
2023-09-11 14:15:52 时间

在这里插入图片描述
https://pintia.cn/problem-sets/994805342720868352/problems/994805367987355648
首先: 要知道二叉搜索树的中序遍历是有序的
故可以将数组先排序,然后按照中序遍历,遍历树并给树赋值。最后层序遍历输出即可。

#include<bits/stdc++.h>
using namespace std;
const int N=1e3+10;
unordered_map<int,int>l,r;
int n,a[N],idx,ans[N];
void dfs(int u)
{
    if(l[u]!=-1) dfs(l[u]);
    ans[u]=a[idx++];
    if(r[u]!=-1) dfs(r[u]);
}
void print()
{
    queue<int>q; q.push(0);
    vector<int>ve;
    while(q.size())
    {
        int t=q.front(); q.pop();
        ve.push_back(ans[t]);
        if(l[t]!=-1) q.push(l[t]);
        if(r[t]!=-1) q.push(r[t]);
    }
    for(int i=0;i<ve.size();i++) 
    {
        if(i) cout<<" ";
        cout<<ve[i];
    }
}
int main(void)
{
    cin>>n;
    for(int i=0;i<n;i++)
    {
        int id1,id2; cin>>id1>>id2;
        l[i]=id1,r[i]=id2;
    }
    for(int i=0;i<n;i++) cin>>a[i];
    sort(a,a+n);
    dfs(0);
    print();
    return 0;
}