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); } }