用递归算法返回二叉树返回从根节点到叶子结点的路径
时间: 2024-05-06 11:19:58 浏览: 107
以下是Python代码实现:
```python
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def binary_tree_paths(root):
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
left_paths = binary_tree_paths(root.left)
right_paths = binary_tree_paths(root.right)
paths = []
for path in left_paths + right_paths:
paths.append(str(root.val) + "->" + path)
return paths
```
使用方法:
```python
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(5)
print(binary_tree_paths(root)) # ["1->2->5", "1->3"]
```
该函数首先检查根节点是否存在,如果不存在,返回空列表。然后,如果根节点没有左右子节点,返回一个包含根节点值的列表。否则,递归地计算左右子树的路径,将它们与根节点值组合起来,形成完整的路径列表。
阅读全文