Share my Java solution


  • 0
    F
    public class Solution {
    double result=Integer.MAX_VALUE;
    int v=0;
    public int closestValue(TreeNode root, double target) {
        if(root==null) return 0;
        helper(root, target);
        return v;
    }
    public void helper(TreeNode root, double target)
    {
        if(Math.abs(root.val-target)<result)
        {
            v=root.val;
            result=Math.abs(root.val-target);
        }
        if(root.left!=null && target<root.val)
        {
            helper(root.left,target);
        }
        else if(root.right!=null && target>root.val)
        {
            helper(root.right,target);
        }
        
    }
    

    }


  • 0

    Do not rely on Integer.MAX_VALUE. I have added a test case which your code fails.


Log in to reply
 

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