题目
思路与算法
-
112题很容易,相当这是一个简单的DFS问题。
-
112题的递归边界条件为:
Ⅰ root为null。 Ⅱ root的左右子树为null。
-
113题是对输出做了改变,整体思路是一致的。
-
我们需要同时记录当前访问的节点并保存他,边界条件是一致的。
代码实现
112:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null){
return false;
}
sum -= root.val;
if(root.left == null && root.right == null) {
return (sum == 0);
}
return hasPathSum(root.left,sum) || hasPathSum(root.right,sum);
}
}
113:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
// 新建结果集
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
// 双端队列来存放对应的路径数组
Deque<Integer> path = new ArrayDeque<>();
pathSum(root, sum, path, res);
return res;
}
public void pathSum(TreeNode node, int sum, Deque<Integer> path, List<List<Integer>> res) {
// 递归边界条件
if (node == null) {
return;
}
// 从当前sum中减去当前节点的值,再将减去的这个节点值添加到path队列存放
sum -= node.val;
path.addLast(node.val);
if (sum == 0 && node.left == null && node.right == null) {
// 存放到res结果集中
res.add(new ArrayList<>(path));
// 清空path
path.removeLast();
return;
}
pathSum(node.left, sum, path, res);
pathSum(node.right, sum, path, res);
// 递归完成以后,再次清空
path.removeLast();
}
}