Easy recursive Java solution with comments.

  • 0
    public boolean hasPathSum(TreeNode root, int sum) {
    		if (root == null) // base case.
    			return false;
    		if (root.val == sum && root.left == null && root.right == null) // The node should be the leaf node at which the sum is equal to its value.
    			return true;
    		return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); // keep reducing the sum during recursion until it is equal to the value of leaf node.

Log in to reply

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