Accepted Java solution

  • 0

    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;
            left = closestValue(root.left, target);
            right = closestValue(root.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;
            return right;


Log in to reply

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