第四天PAT-A1099 Build A Binary Search Tree算法详解

A1099

Description:

有关二叉查找树BST的描述见题目 A1043 Is It a Binary Search Tree

现给出一个二叉树结构以及一组互不相同的数据,仅存在一种将这些数据填入这颗二叉树的方法使其成为一颗BST,求这颗BST的层次遍历序列。

算法构思:

  1. BST具有中序遍历序列元素值递增的特性
  2. 所给数据序列升序排序后,即得到BST的中序遍历序列
  3. 中序遍历二叉树,依次将遍历到的节点填入数据,二叉树构建完成
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 105;
struct node{
    int key;
    int left;
    int right;
}Node[maxn];
int keys[maxn], ans[maxn];  //存放数据序列及答案
int n, indexx = 0;
void inOrder(int root){ //中序遍历
    if(Node[root].left != -1) inOrder(Node[root].left);
    Node[root].key = keys[indexx++];
    if(Node[root].right != -1) inOrder(Node[root].right);
}
void BFS(){ //广搜层次遍历
    queue<int>q;
    q.push(0);
    while(!q.empty()){
        ans[indexx++] = Node[q.front()].key;
        if(Node[q.front()].left != -1) q.push(Node[q.front()].left);
        if(Node[q.front()].right != -1) q.push(Node[q.front()].right);
        q.pop();
    }
}

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    memset(Node, -1, sizeof(Node));
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
        scanf("%d%d", &Node[i].left, &Node[i].right);
    }
    for(int i = 0; i < n; i++){
        scanf("%d", &keys[i]);
    }
    sort(keys, keys+n);
    inOrder(0);
    indexx = 0;
    BFS();
    for(int i = 0; i < n; i++){
        if(i != 0)
            printf(" ");
        printf("%d", ans[i]);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值