Construction of binary tree according to the preamble and the sequence preorder
Ideas:
In order to find the root sequence according to the preamble sequence, in order to find the sequence of the left and right subtree, then the length of the left and right sub-tree, they found the preamble sequence, the recursive computation.
Code:
"""
使用先序遍历和中序遍历的结果重建二叉树
"""
from collections import deque
class TreeNode(object):
"""
二叉树结点定义
"""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree(object):
"""
二叉树
"""
def __init__(self):
self.root = None
def bfs(self):
ret = []
queue = deque([self.root])
while queue:
node = queue.popleft()
if node:
ret.append(node.val)
queue.append(node.left)
queue.append(node.right)
return ret
def pre_traversal(self):
ret = []
def traversal(head):
if not head:
return
ret.append(head.val)
traversal(head.left)
traversal(head.right)
traversal(self.root)
return ret
def in_traversal(self):
ret = []
def traversal(head):
if not head:
return
traversal(head.left)
ret.append(head.val)
traversal(head.right)
traversal(self.root)
return ret
def post_traversal(self):
ret = []
def traversal(head):
if not head:
return
traversal(head.left)
traversal(head.right)
ret.append(head.val)
traversal(self.root)
return ret
def construct_tree(preorder=None,inorder=None):
if not preorder or not inorder: #空列表不是None ,False,0,'',[],{},()都可以视为假。
return None
#print(preorder,inorder)
#当前根在中序遍历中的下标
index=inorder.index(preorder[0])
#左右子树的中序序列
left=inorder[0:index]
right=inorder[index+1:]
root=TreeNode(preorder[0])
#递归构造
root.left=construct_tree(preorder[1:len(left)+1],left)
root.right=construct_tree(preorder[-len(right):],right)
return root
t = Tree()
root = construct_tree([1, 2, 4, 7, 3, 5, 6, 8], [4, 7, 2, 1, 5, 3, 8, 6])
t.root = root
print (t.bfs())
print (t.pre_traversal())
print (t.in_traversal())
print (t.post_traversal())
Sort of age
Ideas:
Can be seen, although the number of elements a lot, but the value of each element of the relatively small size of the establishment of a number of times each age 100 storage array. Traversing one can know how many times each age. And then output on the line. The time complexity is O (n)
Code:
def sortofage(ages):
oldestage=100
timeofage=[0]*100
for i in range(len(ages)):
timeofage[ages[i]]+=1
index=0
for i in range (oldestage):
for j in range (timeofage[i]):
ages[index]=i
index+=1
return
ages=[88,2,43,44,2,91,2,43]
sortofage(ages)
print(ages)