A = TreeNode("A") B = TreeNode("B") C = TreeNode("C") D = TreeNode("D") E = TreeNode("E") F = TreeNode("F") G = TreeNode("G") H = TreeNode("H") I = TreeNode("I") J = TreeNode("J") K = TreeNode("K") A.left = B A.right = C B.left = D B.right = E D.left = H D.right = I E.right = J C.left = F C.right = G F.right = K
先序遍历
递归:
1 2 3 4 5 6 7 8 9 10 11 12
deffrontorderTraversal(root): res = [] ifnot root: return [] deffrontorder(tree): res.append(tree.val) if tree.left: frontorder(tree.left) if tree.right: frontorder(tree.right) frontorder(root) return res
definorderTraversal(root): res = [] ifnot root: return [] definorder(tree): if tree.left: inorder(tree.left) res.append(tree.val) if tree.right: inorder(tree.right) inorder(root) return res
通用框架——中序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
definorderTraversal( root): result = [] stack = [(1, root)] while stack: go_deeper, node = stack.pop() if node isNone: continue if go_deeper: # 左右节点还需继续深化,并且入栈是先右后左 stack.append((1, node.right)) # 节点自身已遍历,回头可以直接取值 stack.append((0, node)) stack.append((1, node.left)) else: result.append(node.val) return result
defbackorderTraversal(root): res = [] ifnot root: return [] defbackorder(tree): if tree.left: backorder(tree.left) if tree.right: backorder(tree.right) res.append(tree.val) backorder(root) return res
通用框架——后序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
defbackorderTraversal( root): result = [] stack = [(1, root)] while stack: go_deeper, node = stack.pop() if node isNone: continue if go_deeper: stack.append((0, node)) # 左右节点还需继续深化,并且入栈是先右后左 stack.append((1, node.right)) # 节点自身已遍历,回头可以直接取值 stack.append((1, node.left)) else: result.append(node.val) return result