题目
给你二叉树的根节点
root
,返回它节点值的 前序 遍历
解题
# 定义二叉树节点的类
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 前序遍历的递归实现
def preorderTraversal(root: TreeNode) -> list:
result = []
def helper(node):
if node:
result.append(node.val) # 访问根节点
helper(node.left) # 遍历左子树
helper(node.right) # 遍历右子树
helper(root)
return result
# 创建二叉树
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
# 进行前序遍历
traversal_result = preorderTraversal(root)
print(traversal_result) # 输出: [1, 2, 3]