Closest Value in a BST
You are given the root of a binary tree. Return the value in the BST that is closest to the integer target (smallest absolute difference). If two values are equally close, return the smaller one. The tree has at least one node. In a binary search tree every value in a left subtree is smaller than its node and every value in a right subtree is larger.
Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.
Example 1
root [4,2,5,1,3]
target 3
returns 3
3 is in the tree.
Example 2
root [4,2,6,1,3]
target 5
returns 4
4 and 6 are both 1 away; return the smaller, 4.
Constraints
1 <= number of nodes <= 100-1000 <= node.val <= 1000-1000 <= target <= 1000- The tree is a valid binary search tree.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.