Leetcode 270. ( Closest Binary Search Tree Value )

In time, you will call me master -- Star Wars
https://leetcode.com/problems/closest-binary-search-tree-value/

Description (Easy)Given a non-empty binary search tree and a target valueFind Closest value to targetSolutionmaintain a parent_val to store parent valuemaintain a closest_val to store closest nodeCode
# 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 = rightclass Solution:    def closestValue(self, root: TreeNode, target: float) -> int:        target = round(target)        parent_val = closest_val = root.val        while root:            if root.val < target:                root = root.right            elif root.val > target:                root = root.left            else:                return target            if root != None:                if abs(root.val-target) < abs(parent_val-target):                    closest_val = root.val                parent_val = root.val        return closest_val

http://img2.58codes.com/2024/20116751Me2VVlEglf.png


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章