题解 | #牛牛的二叉树问题#

牛牛的二叉树问题

https://www.nowcoder.com/practice/1b80046da95841a9b648b10f1106b04e

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param root TreeNode类 
# @param target double浮点型 
# @param m int整型 
# @return int整型一维数组
#
class Solution:
    def findClosestElements(self , root: TreeNode, target: float, m: int) -> List[int]:
        # write code here
        self.res = []
        self.searchTree(root, target, m)

        ans = [int(target-val) for val in self.res]

        return sorted(ans)


    def searchTree(self, node, target, m):
        if node is None:
            return

        self.findElements(node.val, target, m)
        self.searchTree(node.left, target, m)
        self.searchTree(node.right, target, m)

        
    def findElements(self, val, target, m):
        # print(self.res)
        self.res.append(target - val)
        if len(self.res) > m:
            self.res.sort(key=lambda x:abs(x))
            self.res.pop()

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务