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.node
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.code
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.it
For example:
Given the below binary tree and sum = 22,io
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]class
1.解题思路扩展
本题是上一题的扩展,须要列出全部知足条件的path.咱们只要在递归函数里添加List<Integer> pre参数来存储已经生成的节点序列便可。List
2.代码nw
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); } }