剑指No.34_二叉树中和为某一值的路径
- 题目:输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 target = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
- 忘记考虑负数的情况了,难受
- 其实没太理解清题目要求,题是要求一直到达叶节点的路径之和是否等于目标值,我先理解成了只要路径之和到达了目标值就返回,自然也没考虑出现负数的情况。
List<List<Integer>> result = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
public List<List<Integer>> pathSumWay(TreeNode root, int target){
if (root == null) return result;
if (root.val < target){
target -= root.val;
list.add(root.val);
pathSumWay(root.left, target);
pathSumWay(root.right, target);
list.remove(list.size() - 1);
}else if (root.val == target && root.left == null && root.right == null){
list.add(root.val);
ArrayList<Integer> temp = new ArrayList<>(list);
result.add(temp);
list.remove(list.size() - 1);
}else {
return null;
}
return result;
}
- 正经答案:
List<List<Integer>> result = new LinkedList<>();
LinkedList<Integer> queue = new LinkedList<>();
public List<List<Integer>> pathSumWay(TreeNode root, int target){
recur(root, target);
return result;
}
public void recur(TreeNode root, int target){
if (root == null) return;
queue.add(root.val);
target -= root.val;
if (target == 0 && root.left == null && root.right == null){
result.add(new LinkedList<>(queue));
}
recur(root.left, target);
recur(root.right, target);
queue.removeLast();
}