Python 3中递归实现深度优先遍历返回节点值列表的更优雅方式?
Python中更优雅的递归实现二叉树深度优先遍历(前序)的方式
你当前的代码确实可以正常工作,但try/finally块完全是冗余的——这里没有需要捕获的异常场景,这个结构只会让代码显得臃肿。下面提供几种更简洁、符合Python风格的优化方案:
方案1:移除冗余结构,保留外部传参模式
如果希望继续通过外部传入列表的方式收集结果,可以直接去掉try/finally,简化逻辑:
def depth_first_recursive(root, node_list: list): if not root: return node_list.append(root.val) depth_first_recursive(root.left, node_list) depth_first_recursive(root.right, node_list) return node_list class Node: def __init__(self, val): self.val = val self.left = None self.right = None if __name__ == '__main__': a = Node('a') b = Node('b') c = Node('c') d = Node('d') e = Node('e') f = Node('f') a.left = b a.right = c b.left = d b.right = e c.right = f nodelist = [] print(depth_first_recursive(a, node_list=nodelist))
注:原Node类中的values = []是类属性,实际未被使用,这里直接移除避免混淆。
方案2:纯函数风格(推荐)
更符合Python优雅特性的方式是让函数内部生成结果列表,不需要依赖外部传入的可变对象,避免副作用:
def depth_first_recursive(root): if not root: return [] # 前序遍历逻辑:根节点值 + 左子树遍历结果 + 右子树遍历结果 return [root.val] + depth_first_recursive(root.left) + depth_first_recursive(root.right) class Node: def __init__(self, val): self.val = val self.left = None self.right = None if __name__ == '__main__': a = Node('a') b = Node('b') c = Node('c') d = Node('d') e = Node('e') f = Node('f') a.left = b a.right = c b.left = d b.right = e c.right = f print(depth_first_recursive(a))
这种方式代码极度简洁,调用时无需提前创建列表,直接接收返回结果即可。如果需要实现中序或后序遍历,只需要调整拼接顺序:
- 中序遍历:
depth_first_recursive(root.left) + [root.val] + depth_first_recursive(root.right) - 后序遍历:
depth_first_recursive(root.left) + depth_first_recursive(root.right) + [root.val]
内容的提问来源于stack exchange,提问作者Sirrah
相关产品推荐
相关产品推荐

