7-7 Complete Binary Search Tree(30 分)
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
思路:
1、既满足二叉搜索树,又满足完全二叉树的序列是唯一的。
2、从1写到10,找找规律即可,一般来说,整棵树的根与最下层空缺的数量有关。
3、层序遍历使用队列Queue,poll,取出队列头,add,加入对列尾。
4、从一个数组中取一部分,使用Arrays.copyOfRange(a,from,to).数组从小到大排序使用Arrays.sort(a).
5、level order traversal sequence 层序遍历。
%%%%%%%%%%%%%%%%分割线%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
其实按照搜索树的规律,左子树都比root小,右子树都比root大,即可从给定的N个节点里直接求出root,因为是完全二叉搜索树,他的左子树有多少个几点是确定的!
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int [] a = new int [n];
for(int i=0 ; i <n ; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
Queue<int [] > st = new LinkedList<>();
st.add(a);
int flag= 0;
while(!st.isEmpty()) {
int [] temp = st.poll();
int p = root(temp);
if(p!=0)
{
if(flag!=0)
System.out.print(" ");
System.out.print(temp[p-1]);
flag =1;
int [] left = Arrays.copyOfRange(temp, 0, p-1);
int [] right = Arrays.copyOfRange(temp,p, temp.length);
st.add(left);
st.add(right);
}
}
}
private static int root(int[] a) {
// TODO Auto-generated method stub
int n = a.length;
int dp = (int)(Math.log(n)/Math.log(2))+1;
int m =(int) (n-(Math.pow(2, dp-1)-1));
int max = (int) Math.pow(2, dp-1);
int root =0;
if(m<(double)max/2) {
int temp = (int) Math.pow(2, dp-2);
root = temp+m;
}
else
root = (int) Math.pow(2, dp-1);
return root;
}
}