defreconstruct_from_levelOrder(levelorder,index): if levelorder[index]==-1: return root = TreeNode(levelorder[index]) left = 2*index+1 right = 2*index+2 if left<len(levelorder): root.left = reconstruct_from_levelOrder(levelorder,left) if right<len(levelorder): root.right = reconstruct_from_levelOrder(levelorder,right) return root
defpreOrder_(root): result = [] stack = [] while stack or root: while root: stack.append(root) result.append(root.val) root = root.left root = stack.pop() root = root.right print(result)
1 2 3 4 5 6 7 8 9 10 11 12
definOrder_(root): result = [] stack = []
while stack or root: while root: stack.append(root) root = root.left root = stack.pop() result.append(root.val) root = root.right print(result)
1 2 3 4 5 6 7 8 9 10 11 12
defpostOrder_(root): stack1 = [] stack2 = [] stack1.append(root) while stack1: node = stack1.pop() stack2.append(node.val) if node.left: stack1.append(node.left) if node.right: stack1.append(node.right) print(stack2[::-1])
1 2 3 4 5 6 7 8 9 10 11 12
defpostOrder_2(root): result = [] stack = [] while stack or root: while root: stack.append(root) result.append(root.val) root = root.right root = stack.pop() root = root.left print(result[::-1])
1 2 3 4 5 6 7 8 9 10 11 12 13
deflevelOrder_(root): queue = [root] result = []
while queue: temp = [] for _ in range(len(queue)): node = queue.pop(0) result.append(node.val) if node.left : temp.append(node.left) if node.right: temp.append(node.right) queue.extend(temp) print(result)
面鲸公众号的神奇框架
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defpreOrder_mianjing(root): stack = [] stack.append((root,False)) result = []
while stack: root,visited = stack.pop() ifnot root: continue if visited: result.append(root.val) else: stack.append((root.right,False)) stack.append((root.left,False)) stack.append((root,True)) print(result)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
definOrder_mianjing(root): stack = [] stack.append((root,False)) result = []
while stack: root,visited = stack.pop() ifnot root: continue if visited: result.append(root.val) else: stack.append((root.right,False)) stack.append((root,True)) stack.append((root.left,False)) print(result)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defpostOrder_mianjing(root): stack = [] stack.append((root,False)) result = []
while stack: root,visited = stack.pop() ifnot root: continue if visited: result.append(root.val) else: stack.append((root,True)) stack.append((root.right,False)) stack.append((root.left,False)) print(result)