pygorithm/tree/tree_order.py

48 lines
1.0 KiB
Python
Raw Permalink Normal View History

2023-12-19 17:40:11 +08:00
from .binary_tree import TreeNode
"""
二叉树的遍历层序遍历一层一层的遍历方向为从左到右或从右到左
"""
def level_order(root: TreeNode):
q = [root]
res = []
while q:
node = q.pop(0)
res.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return res
"""
二叉树遍历前序中序后序遍历都属于深度优先遍历 depth-first traversal, DFS
前序先遍历根节点再遍历左节点再遍历右节点
中续先遍历左节点再遍历根节点再遍历右节点
后续先左再右后中
"""
def pre_order(root: TreeNode):
# 前序遍历
print(root.val)
if root.left:
pre_order(root.left)
if root.right:
pre_order(root.right)
def in_order(root: TreeNode):
in_order(root.left)
print(root.val)
in_order(root.right)
def post_order(root: TreeNode):
post_order(root.left)
post_order(root.right)
print(root.val)