Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
1.解题思路
利用递归,对于每个根节点,只要左子树和右子树中有一个满足,就返回true;
每次访问一个节点,就将sum-该节点的val,作为新的Sum进行下一层的判断。
直到叶子节点,且sum与节点val相等,则表示存在这样的path,返回true.
2.代码
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null)return false;
if(root.val==sum&&root.left==null&&root.right==null) return true;
return hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum-root.val);
}
}
Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For 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]
]
1.解题思路
本题是上一题的扩展,需要列出所有满足条件的path.我们只要在递归函数里添加List<Integer> pre参数来存储已经生成的节点序列即可。
2.代码
public class Solution {
List<List<Integer>> res=new ArrayList<List<Integer>>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root==null) return res;
helper(root,sum,new ArrayList<Integer>());
return res;
}
private void helper(TreeNode root, int sum,List<Integer> pre){
if(root==null) return;
List<Integer> cur=new ArrayList<Integer>(pre);
cur.add(root.val);
if(root.left==null&&root.right==null&&sum==root.val){
res.add(cur);
return;
}
helper(root.left,sum-root.val,cur);
helper(root.right,sum-root.val,cur);
}
}
Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
1.解题思路
本题的不同点是path可以不从root开始,不到leaf结束。但由于可以存在负数节点,所以没法通过比较大小来缩进节点,所以我们就只能考虑从每一个节点开始的情况。
2.代码
public class Solution {
public int pathSum(TreeNode root, int sum) {
if(root==null) return 0;
//helper(root,sum) 当前节点开始
//pathSum(root.left,sum) 当前节点左节点开始
//pathSum(root.right,sum) 当前节点右节点开始
return helper(root,sum)+pathSum(root.left,sum)+pathSum(root.right,sum);
}
private int helper(TreeNode root,int sum){
if(root==null) return 0;
int count=0;
if(root.val==sum) count++;
return count+helper(root.left,sum-root.val)+helper(root.right,sum-root.val);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。