Most 3-line solutions did not pass this corner case. Use long instead of int!

  • 0

    Even the sample program gives the wrong output in this case.
    [1, 2147483647]

    Use long instead of int to to solve the problem recursively;

    public boolean hasPathSum(TreeNode root, int sum) {
        return safeSearch(root, (long)sum);
    public boolean safeSearch(TreeNode root, long sum) {
        if(root == null) return false;
        if(root.left == null && root.right == null) return sum == root.val;
        return safeSearch(root.left, sum - root.val) || safeSearch(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.