Simple recursive java solution


  • 0
    M
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root==null){
                return false;
            }
            boolean temp = sumFinder(root, root.val, sum);
            return temp;
        }
        private boolean sumFinder(TreeNode root, int currSum, int sum){
            if(root==null && currSum!=sum){
                return false;
            } 
            if(currSum==sum && (root.left==null && root.right==null)){
                return true;
            }
            if(root.left!=null && root.right!=null){
                return (sumFinder(root.left, currSum+root.left.val, sum)||sumFinder(root.right, currSum+root.right.val, sum));
            }
            if(root.left==null && root.right!=null){
                return sumFinder(root.right, currSum+root.right.val, sum);
            }
            if(root.left!=null && root.right==null){
                return (sumFinder(root.left, currSum+root.left.val, sum));
            }
            return false;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.