难度系数 ⭐⭐⭐难在思路
时间限制 C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
题目内容 输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路 递归遍历,在每一次深入遍历时,目标数值将会变化,即目标数值-当前数值,若遍历至叶子节点,且此时目标数值变化为0,则该路径即为待查找的路径。
package nowcoder;
import java.util.ArrayList;
public class No26 {
private ArrayList<ArrayList<Integer>> res = new ArrayList<>();
private ArrayList<Integer> path = new ArrayList<>();
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
if (root == null) return res;
target -= root.val;
path.add(root.val);
if (root.left == null && root.right == null && target == 0)
res.add(new ArrayList<Integer>(path)); // 若写作res.add(path),最终res中的path将不会有数值
if (root.left != null) res = FindPath(root.left, target);
if (root.right != null) res = FindPath(root.right, target);
path.remove(path.size() - 1);
return res;
}
public static void main(String[] args){
TreeNode head = new TreeNode(1);
head.left = new TreeNode(2);
head.right = new TreeNode(3);
head.left.left = new TreeNode(4);
head.left.right = new TreeNode(5);
head.right.left = new TreeNode(6);
head.right.right = new TreeNode(7);
head.right.right.right = new TreeNode(8);
// System.out.println(FindPath(head, 8));
}
}