/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func closestValue(root *TreeNode, target float64) int {
var dfs func(*TreeNode,float64)
ans:=0
minValue:=math.MaxFloat64
dfs = func(node *TreeNode,target float64){
if node==nil{
return
}
dfs(node.Left,target)
nodeValue:=float64(node.Val)
if abs(nodeValue-target)<minValue{
minValue = abs(nodeValue-target)
ans = node.Val
}
dfs(node.Right,target)
}
dfs(root,target)
return ans
}
func min(a,b float64) float64{
if a<b{
return a
}
return b
}
func abs(x float64) float64{
if x<0{
return -x
}
return x
}
# 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 = right
class Solution:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
node = root
res = root.val
has_change = True
while has_change:
has_change = False
res = min(res, node.val,key=lambda x:(abs(x - target), x))
if node.left is not None and target < node.val:
node = node.left
has_change = True
elif node.right is not None and target > node.val:
node = node.right
has_change = True
return res