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.
样例输入为:`
10
1 2 3 4 5 6 7 8 9 0
输出为:
6 3 8 1 5 7 9 0 2 4
在解决这道题时,看了陈越老师的mooc,对于基本的算法框架有了掌握,用了大约1个多小时把框架搭好了,但是如何输出呢?想到了Python中的字典,因此将每一层先用字典储存:
{'1': [6], '2': [3, 8], '3': [1, 5, 7, 9], '4': [0, 2, 4]}
其中key是层数,value是具体值。最后按照遍历顺序输出即可。
但实际上,作为小白,想去很快的解决掉这个问题真的不容易。前前后后花了两天时间,4-5个小时去做。
而且百度了许久,也没找到用python写的,所以我把这篇帖子放了出来,供大家参考。
import sys
import numpy as np
#输入部分
n=int(input())
case=sys.stdin.readline().split()
case=sorted([int(i) for i in case])
#print(case)
tree_dic={}#用来储存每一层的对应的元素
#获取完全二叉树的度,度为h+1
def getleftright(n):
h=int(np.log2(n+1))
left=np.power(2,h-1)
x=n-(np.power(2,h)-1)
if x<=left:
L=np.power(2,h-1)-1+x
else:
L=np.power(2,h)-1
return L
#主函数
def solve(Aleft,Aright,Troot,ceng=1):
n=Aright-Aleft+1
#print("length:"+str(n))
if n<=0:
return
if n==1:
Troot=Aleft
case[Troot]#print the root
if str(ceng) in tree_dic.keys():
tree_dic[str(ceng)].append(case[Troot])
else:
tree_dic[str(ceng)]=[case[Troot]]
#print(tree_dic)
return
L=getleftright(n)
R=n-L-1
Troot=Aleft+L
case[Troot]#print the root
if str(ceng) in tree_dic.keys():
tree_dic[str(ceng)].append(case[Troot])
else:
tree_dic[str(ceng)]=[case[Troot]]
#print(tree_dic)
ceng+=1
solve(Aleft,L-1+Aleft,Aleft,ceng)#left tree
solve(Aleft+L+1,Aleft+L+1+R-1,L+1,ceng)#right tree
solve(0,n-1,0,1)
##输出部分
first_flg=False
for ceng_i in tree_dic.values():
for i in ceng_i:
if first_flg==True:
print(' ',end='')
print(i,end='')
else:
print(i,end='')
first_flg=True
print('')