根据前序和中序遍历序列构建二叉树
思路:
根据前序序列找到根在中序序列中的位置,从而找到左右子树的中序序列,再根据左右子树的长度,找到它们的前序序列,递归计算。
代码:
""" 使用先序遍历和中序遍历的结果重建二叉树 """ 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())
年龄排序
思路:
可以看到,虽然元素的个数很多,但每个元素的值比较小,建立一个大小为100的数组存放每个年龄的次数。遍历一次就可以知道每个年龄的次数。再输出就行。时间复杂度为O(n)
代码:
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)
来源:https://www.cnblogs.com/void-lambda/p/12330247.html