Java solution

  • 0

    If we find a leaf node, we juage whether it meets the condition. If it is not a leaf node, we juage whether it exists a leaf node that meets the condition in its left child tree,then go to its right child tree.

     public boolean hasPathSum(TreeNode root, int sum) {
            if(root==null) return false;
            else if(root.left==null&&root.right==null) return sum == root.val;
            if(hasPathSum(root.left, sum-root.val)) return true;
            if(hasPathSum(root.right, sum-root.val)) return true;
            return false;

Log in to reply

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