编程求从二叉树根结点到到指定结点p之间的路径
时间: 2024-01-29 16:04:33 浏览: 69
以下是Python代码实现:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def find_path(root, p):
if not root:
return []
if root.val == p.val:
return [root.val]
left_path = find_path(root.left, p)
if left_path:
return [root.val] + left_path
right_path = find_path(root.right, p)
if right_path:
return [root.val] + right_path
return []
# 测试代码
root = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
node7 = TreeNode(7)
root.left = node2
root.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
p = node5
path = find_path(root, p)
print(path)
```
输出:
```
[1, 2, 5]
```
其中,`find_path`函数的参数为二叉树的根节点`root`和指定节点`p`,返回值为从根节点到指定节点的路径。如果找不到指定节点,则返回空列表。
阅读全文