What's wrong with this code?


  • 0
    G

    The code below passed 65/66 test cases, but got stuck with the last case. Any ideas?

    Input: [1500000000,1400000000], -1500000000.0

    Output: 1500000000

    Expected: 1400000000

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int closestValue(TreeNode root, double target) {
            // considering the tree has integers and target is float
            TreeNode closestNode = root;
            double dist = Integer.MAX_VALUE;
            
            while(root != null) {
                if(Math.abs(target - root.val) < 0.5) {
                    return root.val;
                }
                if(Math.abs(target - root.val) < dist) {
                    dist = Math.abs(target - root.val);
                    closestNode = root;
                }
                
                if(target < root.val) {
                    root = root.left;
                } else {
                    root = root.right;
                }
            }
            
            return closestNode.val;
        }
    }

  • 0
    M

    try
    double dist = abs(target - root->val);

    int.MAX_VALUE is not big enough to cover all possible differences, just like this case. either difference is higher than int.MAX_VALUE.


Log in to reply
 

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