题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
要求找出所有从根到叶子的节点之和为sum的路径。感觉跟前一题有点像,但是这道题要求找出所有可能的情况并返回,于是就想到了类似于回溯的方法。但是在写回溯的add/remove的时候还是卡住了,知道要在遇到叶子的val == sum的时候加入result集,但是不知道怎么普通的加加减减。如果遇到一个非叶子节点,需要check它有没有左右子树,如果有的话就要沿着这边继续遍历,没有其中一边的话其实啥也不用干(这里没有完全理解透)。继续遍历结束以后要把它给remove掉。
Runtime: 1 ms, faster than 100.00% of Java online submissions for Path Sum II.
Memory Usage: 38.8 MB, less than 5.03% of Java online submissions for Path Sum II.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
recursion(root, sum, result, new ArrayList<>());
return result;
}
private void recursion(TreeNode root, int sum, List<List<Integer>> result, List<Integer> temp) {
if (root == null) {
return;
}
temp.add(root.val);
if (root.val == sum && root.left == null && root.right == null) {
result.add(new ArrayList<>(temp));
return;
}
if (root.left != null) {
recursion(root.left, sum - root.val, result, temp);
temp.remove(temp.size() - 1);
}
if (root.right != null) {
recursion(root.right, sum - root.val, result, temp);
temp.remove(temp.size() - 1);
}
}
}
其他方法暂时放弃。
2020.10.21 二刷
磕磕绊绊差一点就写出来了,最后的remove的地方刚开始还是没搞对,直接递归完就remove了一次,结果发现给的test case结果多了个节点,看了下笔记感觉好像想通了。实际上是每次add完都要及时remove掉,如果单边有子节点,那在递归函数中就会把它加到temp里,等这次递归完了还需要把它remove掉,那就只能在调用它之后remove。如果单边没有子节点,那递归的时候直接return了并没有加它,所以就不用remove掉。代码跟上次一样就不po了。