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 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 boolean has; 12 public boolean hasPathSum(TreeNode root, int sum) { 13 // Start typing your Java solution below 14 // DO NOT write main() function 15 has = false; 16 path(root, sum); 17 return has; 18 } 19 public void path(TreeNode r, int s){ 20 if(r == null) return; 21 if(r.left == null && r.right == null){ 22 if(r.val == s)has = true; 23 return; 24 } 25 else{ 26 path(r.right, s - r.val); 27 path(r.left, s - r.val); 28 } 29 } 30 }
第二遍:
1 public class Solution { 2 public boolean hasPathSum(TreeNode root, int sum) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 if(root == null) return false; 5 sum -= root.val; 6 if(root.left == null && root.right == null){ 7 if(sum == 0) return true; 8 else return false; 9 } 10 return hasPathSum(root.left , sum) || hasPathSum(root.right, sum); 11 } 12 }
if(root == null) return false; 很重要!
posted on 2013-09-12 13:02 Step-BY-Step 阅读(135) 评论(0) 编辑 收藏 举报