PAT Complete Binary Search Tree

学数据结构的时候刷到的一道题,感觉和平时的思路不大一样。并且涉及到完全二叉树上一个重要特性——根据下标访问父节点、子节点。

题目概述:

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

 

  • The left subtree of a node contains only nodes with keys less than the node's key. 

     

     

  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key. 

     

     

  • Both the left and right subtrees must also be binary search trees.

     

    A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

    Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

解题思路为先将输入的数据排序,快排之类的可以调用c语言自带的库函数qsort,也可以自己写。

此外由于二叉树的特性不难发现从小到大排序后的数列为树的中序遍历结果,记为a[]。结合完全二叉树的特性,可以将每一个结点标上下标,中序遍历完全二叉树输出下标的结果存储在b[]。c[b[i]]=a[i]。c[]就是存储该完全二叉树的数组。

要得到中序遍历的树的下标也很简单,从i=1开始,i*2为左儿子的下标,i*2+1为右儿子的下标。

**中序遍历,先递归左儿子,再处理根节点,再递归处理右儿子。

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1000
int data[MAXSIZE];
int tree[MAXSIZE];
int pos=1;
void build(int data,int size);
int cmp(const void*,const void*);
int  main(void)
{
    int num;
    int temp;
    int i=0;
    scanf("%d",&num);
    temp=num;
    while(num--)
    {
        scanf("%d",&data[++i]);
    }
    qsort(data+1, i, sizeof(int),cmp);
    build(1, i);
    for(i=1;i<temp;i++)
    {
        printf("%d ",tree[i]);
    }
    printf("%d\n",tree[i]);
}

int cmp(const void*a,const void*b)
{
    return *(int*)a-*(int*)b;
}

void build(int root,int size)
{
    if(root>size)
        return;
    build(root*2, size);
    tree[root]=data[pos++];
    build(root*2+1,size);
}

 

Sample Input:

10

1 2 3 4 5 6 7 8 9 10

Sample Output:

6 3 8 1 5 7 9 0 2 4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值