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.
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
这道题目想了很久,主要是如何建立这棵完全搜索二叉树,一开始不知道如何下手。陈越老师分析思路如下:
首先选择何种数据结构来存?数组 or 链表
从空间上考虑,本题由于是完全二叉树,数组的存储相当划算,甚至比链表还好,因为链表还要涉及指针域的空间;从时间上考虑,本题涉及对数组的操作是层次遍历,如果按照链表存储需要使用队列,而如果使用数组则只需要遍历数组即可!!!
因此使用数组一石二鸟。
建立这棵二叉树
由于是二叉搜索树,因此每个根节点值大于左子树,大于右子树,因此只需要将原输入序列排序,找到根节点应存放元素的下标(一般的二叉搜索树是不可求的,而这对于完全二叉树是可求的!!!),在将该元素赋值给根节点即可。
易错点
二叉树的高度是
k=int(math.log(N,2))+1
注意是向下取整后加一,而不是直接向上取整
或者
k=math.ceil(math.log(N+1,2))
N+1求对数后直接向上取整
二者有区别。
求根节点元素在有序序列中的下标表达式
如果只考虑了N-(2**(k-1)-1),那就是认为最下一层的叶子节点全部放在左子树上,这是不正确的。
N=len(L)
k=int(math.log(N,2))+1
idx=2**(k-2)-1+min(2**(k-2),N-(2**(k-1)-1))
注意树的高度为1,2对应节点数目1,2,3时上述公式不成立,单独拿出来。
代码
import math
def solve(L,tree,root):
if L!=[]:
N=len(L)
k=int(math.log(N,2))+1
idx=0
if k>=3:
idx=2**(k-2)-1+min(2**(k-2),N-(2**(k-1)-1))
elif k==2:
idx=1
elif k==1:
idx=0
tree[root]=L[idx]
solve(L[:idx],tree,2*root+1)#处理左子树
solve(L[idx+1:],tree,2*root+2)#处理右子树
N=int(input())
L=list(map(int,input().split()))
L.sort()
if N==1:
print(L[0])
elif N==2:
print(str(L[1])+' '+str(L[0]))
elif N==3:
print(str(L[1])+' '+str(L[0])+' '+str(L[2]))
else:
tree=[0 for i in range(N)]
solve(L,tree,0)
print(' '.join(map(str,tree)))