算法dfs——二叉搜索树中最接近的值 II
901. 二叉搜索树中最接近的值 II
给定一棵非空二叉搜索树以及一个target值,找到 BST 中最接近给定值的 k 个数。
样例
样例 1:
输入:
{1}
0.000000
1
输出:
[1]
解释:
二叉树 {1},表示如下的树结构:
1
样例 2:
输入:
{3,1,4,#,2}
0.275000
2
输出:
[1,2]
解释:
二叉树 {3,1,4,#,2},表示如下的树结构:
3
/ \
1 4
\
2
挑战
假设是一棵平衡二叉搜索树,你可以用时间复杂度低于O(n)的算法解决问题吗( n 为节点个数)?
注意事项
- 给出的target值为浮点数
- 你可以假设
k总是合理的,即k ≤ 总节点数 - 我们可以保证给出的 BST 中只有
唯一一个最接近给定值的 k 个值的集合
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
""" class Solution:
"""
@param root: the given BST
@param target: the given target
@param k: the given k
@return: k values in the BST that are closest to the target
"""
def closestKValues(self, root, target, k):
if root is None or k == 0:
return [] nums = self.get_inorder(root)
left = self.find_lower_index(nums, target)
right = left + 1
results = []
for _ in range(k):
if (right >= len(nums)) or (left >=0 and target - nums[left] < nums[right] - target):
results.append(nums[left])
left -= 1
else:
results.append(nums[right])
right += 1
return results def get_inorder(self, root):
result = []
stack = []
node = root
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
result.append(node.val)
node = node.right
return result def find_lower_index(self, nums, target):
"""
find the largest number < target, return the index
"""
start, end = 0, len(nums) - 1
while start + 1 < end:
mid = (start + end) // 2
if nums[mid] < target:
start = mid
else:
end = mid if nums[end] < target:
return end if nums[start] < target:
return start return -1
更优的解法,todo
相关的题目:
11. 二叉查找树中搜索区间
给定一个二叉查找树和范围[k1, k2]。按照升序返回给定范围内的节点值。
样例
样例 1:
输入:{5},6,10
输出:[]
5
它将被序列化为 {5}
没有数字介于6和10之间
样例 2:
输入:{20,8,22,4,12},10,22
输出:[12,20,22]
解释:
20
/ \
8 22
/ \
4 12
它将被序列化为 {20,8,22,4,12}
[12,20,22]介于10和22之间
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
""" class Solution:
"""
@param root: param root: The root of the binary search tree
@param k1: An integer
@param k2: An integer
@return: return: Return all keys that k1<=key<=k2 in ascending order
"""
def searchRange(self, root, k1, k2):
# write your code here
"""
# recursive solution
if not root:
return []
if root.val < k1:
return self.searchRange(root.right, k1, k2)
elif root.val > k2:
return self.searchRange(root.left, k1, k2)
else:
return self.searchRange(root.left, k1, k2) + [root.val] + \
self.searchRange(root.right, k1, k2)
""" result = []
q = [root] while q:
node = q.pop()
if not node:
continue if k1 <= node.val <= k2:
result.append(node.val)
q.append(node.left)
q.append(node.right)
elif node.val < k1:
q.append(node.right)
else:
q.append(node.left) result.sort()
return result
85. 在二叉查找树中插入节点
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例
样例 1:
输入: tree = {}, node= 1
输出: {1}
样例解释:
在空树中插入一个点,应该插入为根节点。
样例 2:
输入: tree = {2,1,4,3}, node = 6
输出: {2,1,4,3,6}
样例解释:
如下:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
挑战
能否不使用递归?
注意事项
保证不会出现重复的值
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
""" class Solution:
"""
@param: root: The root of the binary search tree.
@param: node: insert this node into the binary search tree
@return: The root of the new binary search tree.
"""
def insertNode(self, root, target):
# write your code here
if not root:
return target node = root
while node:
if target.val > node.val:
if node.right is None:
node.right = target
return root
node = node.right
elif target.val < node.val:
if node.left is None:
node.left = target
return root
node = node.left
return root
另外递归的解法也很优雅:
"""
在树上定位要插入节点的位置。 如果它大于当前根节点,则应该在右子树中,
如果它小于当前根节点,则应该在左子树中。
(二叉查找树中保证不插入已经存在的值)
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: node: insert this node into the binary search tree
@return: The root of the new binary search tree.
"""
def insertNode(self, root, node):
# write your code here
return self.__helper(root, node) # helper函数定义成私有属性
def __helper(self, root, node):
if root is None:
return node
if node.val < root.val:
root.left = self.__helper(root.left, node)
else:
root.right = self.__helper(root.right, node)
return root
算法dfs——二叉搜索树中最接近的值 II的更多相关文章
- LeetCode701 二叉搜索树中插入结点
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树. 返回插入后二叉搜索树的根节点. 保证原始二叉搜索树中不存在新值. 注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜 ...
- [Swift]LeetCode701. 二叉搜索树中的插入操作 | Insert into a Binary Search Tree
Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert t ...
- Leetcode 701. 二叉搜索树中的插入操作
题目链接 https://leetcode.com/problems/insert-into-a-binary-search-tree/description/ 题目描述 给定二叉搜索树(BST)的根 ...
- Java实现 LeetCode 701 二叉搜索树中的插入操作(遍历树)
701. 二叉搜索树中的插入操作 给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树. 返回插入后二叉搜索树的根节点. 保证原始二叉搜索树中不存在新值. 注意,可能存在多种有效的插入 ...
- [Swift]LeetCode450. 删除二叉搜索树中的节点 | Delete Node in a BST
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Retur ...
- LeetCode:二叉搜索树中第K小的数【230】
LeetCode:二叉搜索树中第K小的数[230] 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 说明:你可以假设 k 总是有效的,1 ≤ k ...
- Java实现 LeetCode 450 删除二叉搜索树中的节点
450. 删除二叉搜索树中的节点 给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变.返回二叉搜索树(有可能被更新)的根节点的引 ...
- [LeetCode]230. 二叉搜索树中第K小的元素(BST)(中序遍历)、530. 二叉搜索树的最小绝对差(BST)(中序遍历)
题目230. 二叉搜索树中第K小的元素 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 题解 中序遍历BST,得到有序序列,返回有序序列的k-1号元素. 代 ...
- 刷题-力扣-230. 二叉搜索树中第K小的元素
230. 二叉搜索树中第K小的元素 题目链接 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a ...
随机推荐
- libevent笔记3:evbuffer
evbuffer 之前提到bufferevent结构体提供两个缓存区用来为读写提供缓存,并自动进行IO操作.这两个缓存区是使用Libevent中的evbuffer实现的,同样,Libevent中也提供 ...
- Spring Cloud Zuul 精进
接着上一篇继续讲Zuul,上一篇搭建了Zuul的环境简单说明了怎么使用,本篇查缺补漏将一些常用的配置贴出来.文末我们会一起分析一下Zuul的源码,升华一下本篇的格调! 忽略所有微服务或某些微服务 默认 ...
- Ribbon核心组件IRule及配置指定的负载均衡算法
Ribbon在工作时分为两步: 第一步:先选择 EurekaServer,它优先选择在同一个区域内负载较少的Server: 第二步:再根据用户指定的策略,在从Server取到的服务注册列表中选择一个地 ...
- idea从github导入maven项目
原文地址:https://blog.csdn.net/dianyongpai3113/article/details/82784716 之后next.finish就好了
- Python下的XML-RPC客户端和服务端实现(基于xmlrpclib SimpleXMLRPCServer 模块)
RPC是Remote Procedure Call的缩写,翻译成中文就是远程方法调用,是一种在本地的机器上调用远端机器上的一个过程(方法)的技术,这个过程也被大家称为“分布式计算”,是为了提高各个分立 ...
- hanlp进行命名实体识别
需要安装jpype先,这个是python调用java库的桥梁. # -*- coding: utf-8 -*- """ Created on Thu May 10 09: ...
- Python3+PyCryptodome实现各种加密算法教程
一.说明 PyCryptodome是python一个强大的加密算法库,可以实现常见的单向加密.对称加密.非对称加密和流加密算法.直接pip安装即可: pip install pycryptodome ...
- Ext.net自动保存读取GrdPanel列显示状态
//layout保存 function SaveLayOut() { let colVisibleArray = []; for (var i = 0; i < mcp_gridlist.col ...
- Java学习:等待唤醒机制
等待唤醒机制 线程的状态 NEW 至今尚未启动的线程处于这种状态 RUNNABLE 正在Java虚拟机中执行的线程处于这种状态 BLOCKED 受阻塞并等待某个监视器锁的线程处于这种状态 WA ...
- CentOS 7 安装 mysql 5.7.27 for zabbix
本文是因为需要安装zabbix系统,才贴出的此步骤,供自己查阅方便之用: 在安装使用zabbix前,需要先安装数据库,这里使用的是MySQL数据库进行部署,给出安装步骤,大家觉得有用也可收藏: 当然安 ...