Recursive Java Solution

  • 0
    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if (root == null) {
                return false;
            // Because this is essentially a root to leaf path , so I must check that
            // I get the sum value at the leaf only and not in the middle of the tree
            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.