My simple iterative solution in Java


  • 0

    Traverse the tree and record the value that is closest to the target (if target value is less than current TreeNode value - go left, go right otherwise).

    public int closestValue(TreeNode focusNode, double target) {
        int result = focusNode.val;
        while (focusNode != null) {
            focusNode = (target < focusNode.val) ? focusNode.left : focusNode.right;
            if (focusNode != null) {
                double diff1 = Math.abs(target - focusNode.val);
                double diff2 = Math.abs(target - result);
                result = diff1 < diff2 ? focusNode.val : result;
            }
        }
        return result;
    }

  • 0
    This post is deleted!

  • 0

    Sorry for that. I updated the question.


  • 0

    Ok, thanks. I'll remove my answer now.


Log in to reply
 

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