求二叉树上结点的路径程序设计
时间: 2024-03-16 18:41:08 浏览: 10
二叉树上结点的路径可以通过递归遍历二叉树实现。具体的程序设计如下:
```java
import java.util.ArrayList;
import java.util.List;
// 定义二叉树结点
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
// 递归遍历二叉树,查找目标结点
private boolean findPath(TreeNode root, int target, List<Integer> path) {
if (root == null) {
return false;
}
// 将当前结点加入路径
path.add(root.val);
// 如果当前结点就是目标结点,则返回 true,表示找到了目标结点
if (root.val == target) {
return true;
}
// 在左子树中查找目标结点
if (findPath(root.left, target, path)) {
return true;
}
// 在右子树中查找目标结点
if (findPath(root.right, target, path)) {
return true;
}
// 如果左右子树都未找到目标结点,则将当前结点从路径中删除
path.remove(path.size() - 1);
return false;
}
// 主函数,查找二叉树根节点到目标结点的路径
public List<Integer> getPath(TreeNode root, int target) {
List<Integer> path = new ArrayList<>();
findPath(root, target, path);
return path;
}
}
```
调用 `getPath` 函数即可得到二叉树根节点到目标结点的路径。例如,对于下面的二叉树:
```
1
/ \
2 3
/ \
4 5
```
如果要查找结点值为 5 的结点,可以这样调用函数:
```java
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
Solution solution = new Solution();
List<Integer> path = solution.getPath(root, 5);
System.out.println(path); // 输出 [1, 2, 5]
```
这样,就可以得到从根节点到结点值为 5 的结点的路径 [1, 2, 5]。