Path Sum: https://oj.leetcode.com/problems/path-sum/
要求解从根到叶子节点的路径的和,首先要从根节点遍历到叶子节点,所以我们需要对树进行深度优先遍历,采用递归的方法解决;每遍历到一个节点,我们将原来的sum减去该节点的值,假如减去某叶子节点的值后,剩余为0,则说明从根节点到该叶子节点的和为原来的sum
代码如下:
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)
return false;
if(sum - root.val == 0 && root.left == null && root.right == null)
return true;
return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
}
}
Path Sum II: https://oj.leetcode.com/problems/path-sum-ii/
这个问题需要找到所有的解,所以我们可以借助辅助存储来存储从根节点到当前节点的路径,因为是深度优先遍历,所以我们采用栈来存储路径上的节点;
代码如下:
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null)
return result;
Stack<Integer> stack = new Stack<Integer>();
path(result, stack, root, sum);
return result;
}
public void path(List<List<Integer>> result, Stack<Integer> stack, TreeNode root, int sum){
if(root == null)
return;
stack.push(root.val);
if(root.left == null && root.right == null){
if(sum - root.val == 0)
result.add(new ArrayList<Integer>(stack));
stack.pop();
return;
}
path(result, stack, root.left, sum-root.val);
path(result, stack, root.right, sum-root.val);
stack.pop();
}
}