Leetcode 112) Path Sum

image

My Answer

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null){return false;}
        return helper(root,targetSum);        
    }
    public boolean helper(TreeNode tn,int sum){
        sum -= tn.val;
        //base case : leaf
        if(tn.left==null && tn.right==null){
            if(sum==0){
                return true;
            }
            return false;
        }
        boolean res;

        if(tn.left==null){
            //tn.right!=null
            res = helper(tn.right,sum);
        }else if(tn.right==null){
            res = helper(tn.left,sum);
        }else{
            res = (helper(tn.right,sum) || helper(tn.left,sum));
        }


        return res;
    }
}

Other Answer

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {

        return hasPathSum(root,targetSum, 0);
    }

    private boolean hasPathSum(TreeNode root, int targetSum, int sumSoFar)
    {
        if(root==null)
            return false;
        sumSoFar += root.val;

        if(sumSoFar == targetSum && root.left == null && root.right==null)
            return true;
        return hasPathSum(root.left, targetSum,sumSoFar ) || hasPathSum(root.right,targetSum,sumSoFar);
    }
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2