Self-explanatory solution

  • 0

    The key to solving this problem is to remember that root==null isn't a leaf node. Imagine a tree with


    A root==null check will return 3 as true if you thought it was the leaf node. Here the code that does it correctly after ensuring we are considering only the leaf nodes:

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

Log in to reply

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