1064. Complete Binary Search Tree (30)

题目链接:http://www.patest.cn/contests/pat-a-practise/1064
题目:

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.

Sample Input:
10
1 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4

分析:
树的建立和层序遍历,关键是要找出根节点对应的数字
AC代码:
#include<stdio.h>
#include<algorithm>
#include<queue>
using namespace std;
struct Node{
 int c;
 Node *lchild;
 Node *rchild;
 Node(){
  this->lchild = NULL;
  this->rchild = NULL;
 }
};
int a[1001];
Node* build(int num, int *a){
 if (num == 0)return NULL;
 else if (num == 1){
  Node *tmp = new Node();//一定要记得初始化。
  tmp->c = *a;
  return tmp;
 }
 else{
  Node *tmp = new Node();
  int idx = 1;
  int ans;//ans是当前树的根节点坐标。
  while (idx - 1 < num)idx = idx * 2;//idx-1的个数为数为完全满二叉树时的数目
  if (num - idx / 2 + 1 <= idx / 4)//如果最后一个叶子节点在左边
   ans = num - idx / 4;
  else
   ans = idx / 2 - 1;
  tmp->c = *(a + ans);//给根节点赋值
  tmp->lchild = build(ans, a);//递归构造左子树
  tmp->rchild = build(num - ans - 1, a + ans + 1);//递归构造右子树
  return tmp;
 }
}
void LevelOrder(Node *R){//用队列来帮助层序遍历树
 queue<Node*>Q;
 Q.push(R);
 bool first_flag = true;
 while (!Q.empty()){
  Node *tmp;
  tmp = Q.front();
  Q.pop();
  if (tmp->lchild)Q.push(tmp->lchild);
  if (tmp->rchild)Q.push(tmp->rchild);
  if (first_flag){
   printf("%d", tmp->c);
   first_flag = false;
  }
  else {
   printf(" %d", tmp->c);
  }
 }
 printf("\n");
}
int main(){
 freopen("F://Temp/input.txt", "r", stdin);
 int n;
 scanf("%d", &n);
 if (n == 0){
  printf("0\n");
  return 0;
 }
 for (int i = 0; i < n; i++){
  scanf("%d", &a[i]);
 }
 sort(a, a + n);
 Node *root;
 root = build(n, a);
 LevelOrder(root);
 return 0;
}


截图:
1064. Complete Binary Search Tree (30)_第1张图片
——Apie陈小旭

你可能感兴趣的:(pat,完全二叉搜索树)