天梯赛练习——Build A Binary Search Tree (30分)(搜索树)

题目:

天梯赛练习——Build A Binary Search Tree (30分)(搜索树)_第1张图片
天梯赛练习——Build A Binary Search Tree (30分)(搜索树)_第2张图片

分析:

递归求解搜索树

代码:

#include 
#include 
#include 
#include 
#include 
using namespace std;

const int MAXN = 105;
int num[MAXN],ans[MAXN];
int n,ind,indx;

struct node
{
    int l=-1,r=-1;
    int val;
}no[MAXN];

void InOrder(int root)
{
    if(no[root].l != -1)
        InOrder(no[root].l);
    no[root].val = num[ind++];
    if(no[root].r != -1)
        InOrder(no[root].r);
}

int main()
{
    scanf("%d",&n);
    int l,r;
    for(int i=0;i<n;++i)
    {
        scanf("%d%d",&l,&r);
        no[i].l = l;
        no[i].r = r;
    }
    for(int i=0;i<n;++i)
        scanf("%d",&num[i]);
    sort(num,num+n);
    InOrder(0);
    queue<int> q;
    q.push(0);
    while(!q.empty())
    {
        int now = q.front();
        q.pop();
        ans[indx++] = no[now].val;
        if(no[now].l != -1)
            q.push(no[now].l);
        if(no[now].r != -1)
            q.push(no[now].r);
    }
    for(int i=0;i<indx;++i)
        if(i == indx-1)
            printf("%d\n",ans[i]);
        else
            printf("%d ",ans[i]);
    return 0;
}

你可能感兴趣的:(#,天梯赛,#,二叉树)