defdfs(root): result = [] pre_order_traversal(root) # 前序遍历 # in_order_traversal(root) # 中序遍历 # post_order_traversal(root) # 后续遍历 return result
defpre_order_traversal(root): ifnot root: return result += [root.val] if root.left: pre_order_traversal(root.left) if root.right: pre_order_traversal(root.right)
defin_order_traversal(root): ifnot root: return if root.left: in_order_traversal(root.left) result += [root.val] if root.right: in_order_traversal(root.right)
defpost_order_traversal(root): ifnot root: return if root.left: post_order_traversal(root.left) if root.right: post_order_traversal(root.right) result += [root.val]
广度优先遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
from collections import deque
defbfs(root): ifnot root: return [] queue = deque() result = [] queue.append(root) while queue: node = queue.popleft() result += [node.val] if node.left: queue.append(node.left) if node.right: queue.append(node.right) return result