题目描述
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
基本思路
通过遍历树的方式找到对应的路径,由于要先加入根节点,所以选用前序遍历。通过一个 stack 保存当前访问的路径,每次访问便压入栈中,访问结束(回到父节点)便将自己(栈顶)弹出。
注意每次保存当前路径需要保存一个副本,否则会在运行时被修改。
以下为具体解答思路:
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> paths = new ArrayList<>();
Stack<Integer> curPath = new Stack<>();
int curSum = 0;
findPathInline(root, target, curSum, curPath, paths);
return paths;
}
void findPathInline(TreeNode root, int target, int curSum,
Stack<Integer> curPath,
ArrayList<ArrayList<Integer>> paths) {
if (root == null) {
return;
}
curPath.push(root.val);
curSum = curSum + root.val;
if (curSum == target && (root.left == null && root.right == null)) {
paths.add(new ArrayList<>(curPath));
} else if (curSum < target) {
findPathInline(root.left, target, curSum, curPath, paths);
findPathInline(root.right, target, curSum, curPath, paths);
}
curPath.pop();
}