PAT Complete Binary Search Tree

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.

 

完全搜索二叉树  

并没有想到什么好方法  按照陈越老师教的方法做的 代码也是参考网易的mooc

用数组来储存完全二叉树 递归的分别寻找左右子树的根节点(此题的难点)

因为知道了一个树的个数 树的左节点个数是能够计算出来

比较复杂

根据数组保存完全二叉树的规律 可得  (2∧H)-1+x=n    此H为除最后一层得总层数  x为最后一层得个数

下面是计算过程

  1.求出H=log(n+1)/log(2)

  2.根据上面的公式 反算出x=n+1-pow(2,h)

  3.比较x和pow(2,h-1) 大小   

  4.算出左子树个数 pow(2,h-1)-1+x

 1 #include <stdio.h>

 2 #include <math.h>

 3 void sort(int a[],int n);

 4 void solve(int left,int right,int root,int a[],int t[]);

 5 int getLeftLength(int n);

 6 int main()

 7 {

 8     int n,i;

 9     int a[1000],t[1000];

10     scanf("%d",&n);

11     for(i=0;i<n;i++)

12         scanf("%d",&a[i]);

13     sort(a,n);

14     solve(0,n-1,0,a,t);

15     printf("%d",t[0]);

16     for(i=1;i<n;i++)

17         printf(" %d",t[i]);

18 }

19 void solve(int left,int right,int root,int a[],int t[])

20 {

21     int leftroot,rightroot,n,len;

22     n=right-left+1;

23     if(n==0)

24         return;

25     len=getLeftLength(n);

26     t[root]=a[left+len];

27     leftroot=root*2+1;

28     rightroot=leftroot+1;

29     solve(left,left+len-1,leftroot,a,t);

30     solve(left+len+1,right,rightroot,a,t);

31 }

32 int getLeftLength(int n)

33 {

34     int h,x,l;

35 

36     h=log(n+1)/log(2);

37     x=n+1-pow(2,h);

38     x=x>pow(2,h-1)?pow(2,h-1):x;

39     l=pow(2,h-1)-1+x;

40     return l;

41 }

42 void sort(int a[],int n)

43 {

44     int i,j,temp;

45     for(i=1;i<n;i++)

46     {

47         for(j=1;j<=n-i;j++)

48         {

49             if(a[j-1]>a[j])

50             {

51                 temp=a[j-1];

52                 a[j-1]=a[j];

53                 a[j]=temp;

54             }

55         }

56     }

57 }

 

 

 

你可能感兴趣的:(Binary search)