Accepted Java solution


  • 0
    D

    This function returns the node value which makes the gap minimum. Notice that function should return the parent node when current node is null. Therefore, the left and right value are intinalized as the root value in the beginning.

    public class Solution {

    // time complexity: o(n)
    public int closestValue(TreeNode root, double target) {
     
        int left = root.val;
        int right = root.val;
        if(root.left!=null)
            left = closestValue(root.left, target);
        if(root.right!=null)
            right = closestValue(root.right, target);
    
        
        if(Math.abs(root.val-target)<=Math.abs(left-target)&&Math.abs(root.val-target)<=Math.abs(right-target))
            return root.val;
        if(Math.abs(root.val-target)>Math.abs(left-target)&& Math.abs(right-target)>Math.abs(left-target))
            return left;
        else 
            return right;
        
    }
    

    }


Log in to reply
 

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