在很多问题中,熟练掌握二叉树的遍历方法,能够轻松解决很多问题。
新建一棵二叉树root=[1,null,2,3]
1、前序遍历
前序遍历的顺序为根节点->左子树->右子树,按照以上二叉树,遍历顺序为[1,2,3]。代码为:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result = []
def traversal(node):
if node == None:
return
result.append(node.val)
traversal(node.left)
traversal(node.right)
traversal(root)
return result
使用迭代实现代码为:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
result.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
2、中序遍历
中序遍历的顺序为左子树->根节点->右子树,按照以上二叉树,遍历顺序为[1,3,2]。代码为:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result = []
def traversal(node):
if node == None:
return
traversal(node.left)
result.append(node.val)
traversal(node.right)
traversal(root)
return result
使用迭代实现代码为:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
stack = []
result = []
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
result.append(root.val)
root = root.right
return result
3、后序遍历
后序遍历的顺序为左子树->右子树->根节点,按照以上二叉树,遍历顺序为[3,2,1]。代码为:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result = []
def traversal(node):
if node == None:
return
traversal(node.left)
traversal(node.right)
result.append(node.val)
traversal(root)
return result
使用迭代实现代码为:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
result.insert(0,node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return result
4、总结
遍历方式 | 顺序 | 特点与应用场景 |
前序遍历 | 根 -> 左 -> 右 | 适合复制二叉树、计算前缀表达式等。 |
中序遍历 | 根 -> 左 -> 右 | 对二叉搜索树(BST)进行中序遍历,结果是有序的。常用于排序或验证二叉搜索树。 |
后序遍历 | 左 -> 右 -> 根 | 适合删除二叉树、计算后缀表达式等。 |