PAT-Build A Binary Search Tree

  • 原题链接:Build A Binary Search Tree
  • 题目大意:给你一个数组,让你将其按照指定的二叉搜索树的结构排序,最后输出这颗二叉搜索树的层次序遍历结果。
  • 解法:原以为还需要我们自己手写二叉搜索树的构建,最后才发现不用,我们只要将这个数组排好序,再对号入座到响应的位置,然后输出遍历结果就好。那我们怎么找到相应的位置呢?
    • 我们可以找到二叉树中每个节点对应的value值,怎么找呢?
    • 我们知道二叉搜索树有下面的性质:右边的点的值都小于它,左边的值都大于它。
    • 所以我们只要就确定右边该节点在中序遍历中属于第几个就可以了。因为对二叉搜索树进行中序遍历就是一个有序的序列。
    • 假设已经排好序的数组是sorted,该节点在中序遍历中属于第i个,则该节点对应的值就是sorted[i]
    • 分析到这里,我们其实就把问题更抽象一步如下:给你一个有序的数列和一颗二叉树的结构,输出这颗二叉搜索树的层次序遍历结果。或者是给定一颗二叉搜索树的结果和中序遍历的结果,输出这颗二叉树的层次序遍历结果。
  • 代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int max_n = 105;
int lchild[max_n];
int rchild[max_n];
int parent[max_n];
int value[max_n];
void init()
{
    for(int i=0;i<max_n;i++)
    {
        lchild[i] = rchild[i] = parent[i] = -1;
    }
}
void display(int root)
{
    queue<int> q;
    q.push(root);
    while(!q.empty())
    {
        int cur_root = q.front();
        q.pop();
        int lindex = lchild[cur_root];
        int rindex = rchild[cur_root];
        if(lindex != -1)
        {
            q.push(lindex);
        }
        if(rindex != -1)
        {
            q.push(rindex);
        }
        if(q.empty())
            cout<<value[cur_root];
        else
            cout<<value[cur_root]<<" ";


    }
}
int calu_lchild_num(int root)
{
    int res = 0;
    if(root == -1)
        return res;
    res += 1;
    int lindex = lchild[root];
    int rindex = rchild[root];
    res += calu_lchild_num(lindex);
    res += calu_lchild_num(rindex);
    return res;

}
void update_value(int root, const int* sort_value, int start)
{
    if(root == -1)
    {
        return ;
    }
    int index = calu_lchild_num(lchild[root]);
    value[root] = sort_value[index + start];

    // cout<<"root is "<<root<<" lchild number is "<< index+start <<" value is "<<value[root]<<endl;
    int lindex = lchild[root];
    int rindex = rchild[root];
    update_value(lindex, sort_value, start);
    update_value(rindex, sort_value, start + index + 1);
}
int main()
{
    init();
    freopen("/home/give/PAT/BuildABinarySearchTree.txt", "r", stdin);
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>lchild[i]>>rchild[i];
        parent[lchild[i]] = i;
        parent[rchild[i]] = i;
    }
    int copy_value[max_n];
    for(int i=0;i<n;i++)
    {
        cin>>value[i];
        copy_value[i] = value[i];
    }
    sort(copy_value, copy_value+n);
    //build_BST(0);
    update_value(0, copy_value, 0);
    display(0);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值