112. Path Sum
给一颗二叉树和一个数,如果有一条从根到叶子结点和等于sum的的路径就返回true。
非常简单,不说了:
int res = 0;
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
if (root.left == null && root.right == null && res + root.val == sum)
return true;
res += root.val;
boolean a = hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
res -= root.val;
return a;
}
113. Path Sum II
和上题几乎一样,只不过要返回所有等于sum的路径。
也不说了:
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
helper(root, sum, res, new ArrayList<>(), 0);
return res;
}
public void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> once, int path) {
if (root == null) return;
if (root.left == null && root.right == null && root.val + path == sum) {
once.add(root.val);
res.add(new ArrayList<>(once));
once.remove(once.size()-1);
return;
}
once.add(root.val);
helper(root.left, sum, res, once, path+root.val);
helper(root.right, sum, res, once, path+root.val);
once.remove(once.size()-1);
}
437. Path Sum III
这题也是找到有多少条路径和等于sum的路径,但是不是从根结点到叶子结点了,而是树中任意的起始结点和任意的结束结点。
终于有点难度了,首先可以暴力求解,就是遍历整棵树,每遍历到一个结点时就求一下以该结点为根结点的树有几条路径。
但是当然不能用这么笨的方法了:
- 可以创建一个hashmap,存储每个根结点到当前结点的路径和temp
- 例如遍历到当前结点为i,路径和为temp
- 然后看一下map中有没有值等于 temp - sum的键值对,比如说有的话,设为j,即从根结点到j结点的路径和为temp - sum,那么说明从j结点到i结点的路径和就是temp - (temp - sum)= sum,那么一遍前序遍历就可以得到结果了。
- 时间复杂度:O(n)
- 空间复杂度:O(n)
public int pathSum(TreeNode root, int sum) {
//初始值
map.put(0, 1);
helper(root, sum, 0);
return res;
}
HashMap<Integer, Integer> map = new HashMap<>();
int res = 0;
public void helper(TreeNode root, int sum, int path) {
if (root == null) return;
int temp = path + root.val;
if (map.containsKey(temp - sum)) {
res += map.get(temp - sum);
}
if (!map.containsKey(temp))
map.put(temp, 0);
map.put(temp, map.get(temp)+1);
helper(root.left, sum, path+root.val);
helper(root.right, sum, path+root.val);
map.put(temp, map.get(temp)-1);
}