Accepted recursive solution in Java


  • 0
    A

    I think my solution is really simple to understand.

    I traversal every path and add the current node's val to num.

    When I meet the leaf, I judge if the num equals sum.

    Finally, return true if there are a root-to-leaf's num equals sum,or return false.

    equals the sum

    public class Solution {
        
        public boolean travel(TreeNode root,int sum,int num)
        {
            num=num+root.val;
            if(root.left==null && root.right==null)
            {
                if(num==sum) return true;
                return false;
            }
            boolean l=false;
            if(root.left!=null) l=travel(root.left,sum,num);
            boolean r=false;
            if(root.right!=null) r=travel(root.right,sum,num);
            if(l || r) return true;
            return false;
        }
        
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root==null) return false;
            return travel(root,sum,0);
        }
    }

  • 4
    K

    you can just use the hasPathSum() method itself to run recursive:

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

  • 0
    A

    Thanks for you comment and your great solution !
    It's so smart !


Log in to reply
 

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