输出二叉树中从每个叶子结点到根结点的路径。
时间: 2023-12-29 17:04:05 浏览: 163
可以使用递归的方式来解决该问题。
首先,我们需要判断当前节点是否为叶子节点。如果是叶子节点,则将该节点的值加入路径中,并输出路径。如果不是叶子节点,则分别对其左子树和右子树进行递归操作。
以下是具体的实现代码:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def print_paths(root):
path = []
print_paths_helper(root, path)
def print_paths_helper(node, path):
if node is None:
return
path.append(node.val)
if node.left is None and node.right is None:
print_path(path)
else:
print_paths_helper(node.left, path)
print_paths_helper(node.right, path)
path.pop()
def print_path(path):
for val in path[::-1]:
print(val, end=" ")
print()
# 测试代码
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
print("二叉树路径如下:")
print_paths(root)
```
输出结果为:
```
二叉树路径如下:
4 2 1
5 2 1
6 3 1
7 3 1
```
阅读全文