Given the root of a binary search tree and a target value, return the value in the BST that is closest to thetarget. If there are multiple answers, print the smallest.
The number of nodes in the tree is in the range [1, 104].
0 <= Node.val <= 109
-109 <= target <= 109
Solutions
Solution 1: Recursion
We define a recursive function dfs(node), which starts from the current node node and finds the node closest to the target value target. We can update the answer by comparing the absolute difference between the current node's value and the target value. If the target value is less than the current node's value, we recursively search the left subtree; otherwise, we recursively search the right subtree.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary search tree.
1 2 3 4 5 6 7 8 91011121314151617181920212223
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defclosestValue(self,root:Optional[TreeNode],target:float)->int:defdfs(node:Optional[TreeNode]):ifnodeisNone:returnnxt=abs(target-node.val)nonlocalans,diffifnxt<diffor(nxt==diffandnode.val<ans):diff=nxtans=node.valnode=node.leftiftarget<node.valelsenode.rightdfs(node)ans=0diff=infdfs(root)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcclosestValue(root*TreeNode,targetfloat64)int{ans:=root.Valdiff:=math.MaxFloat64vardfsfunc(*TreeNode)dfs=func(node*TreeNode){ifnode==nil{return}nxt:=math.Abs(float64(node.Val)-target)ifnxt<diff||(nxt==diff&&node.Val<ans){diff=nxtans=node.Val}iftarget<float64(node.Val){dfs(node.Left)}else{dfs(node.Right)}}dfs(root)returnans}
We can rewrite the recursive function in an iterative form, using a loop to simulate the recursive process. We start from the root node and check whether the absolute difference between the current node's value and the target value is less than the current minimum difference. If it is, we update the answer. Then, based on the size relationship between the target value and the current node's value, we decide to move to the left subtree or the right subtree. The loop ends when we traverse to a null node.
The time complexity is $O(n)$, where $n$ is the number of nodes in the binary search tree. The space complexity is $O(1)$.
1 2 3 4 5 6 7 8 910111213141516
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defclosestValue(self,root:Optional[TreeNode],target:float)->int:ans,diff=root.val,infwhileroot:nxt=abs(root.val-target)ifnxt<diffor(nxt==diffandroot.val<ans):diff=nxtans=root.valroot=root.leftiftarget<root.valelseroot.rightreturnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcclosestValue(root*TreeNode,targetfloat64)int{ans:=root.Valdiff:=math.MaxFloat64forroot!=nil{nxt:=math.Abs(float64(root.Val)-target)ifnxt<diff||(nxt==diff&&root.Val<ans){diff=nxtans=root.Val}iffloat64(root.Val)>target{root=root.Left}else{root=root.Right}}returnans}