BST中第K小的元素

中文English

给一棵二叉搜索树,写一个 KthSmallest 函数来找到其中第 K 小的元素。

Example

样例 1:

输入:{1,#,2},2
输出:2
解释:
1
\
2
第二小的元素是2。

样例 2:

输入:{2,1,3},1
输出:1
解释:
2
/ \
1 3
第一小的元素是1。

Challenge

如果这棵 BST 经常会被修改(插入/删除操作)并且你需要很快速的找到第 K 小的元素呢?你会如何优化这个 KthSmallest 函数?

Notice

你可以假设 k 总是有效的, 1 ≤ 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 k: the given k
@return: the kth smallest element in BST
""" """
nth = 0
result = None def kthSmallest(self, root, k):
# write your code here
self.dfs(root, k)
return self.result def dfs(self, root, k):
if not root:
return
self.dfs(root.left, k)
self.nth += 1
if self.nth == k:
self.result = root.val
self.dfs(root.right, k) """ """ template:
TreeNode pNode = root;
while (!s.isEmpty() || pNode != null) {
if (pNode != null) {
s.push(pNode);
pNode = pNode.left;
} else {
pNode = s.pop();
result.add(pNode.val);
pNode = pNode.right;
}
}
"""
def kthSmallest(self, root, k):
if not root:
return None
q = []
node = root
nth = 0
while q or node:
if node:
q.append(node)
node = node.left
else:
node = q.pop()
nth += 1
if nth == k:
return node.val
node = node.right
return None

  

86. 二叉查找树迭代器

中文
English

设计实现一个带有下列属性的二叉查找树的迭代器:
next()返回BST中下一个最小的元素

  • 元素按照递增的顺序被访问(比如中序遍历)
  • next()hasNext()的询问操作要求均摊时间复杂度是O(1)

样例

样例 1:

输入:{10,1,11,#,6,#,12}
输出:[1, 6, 10, 11, 12]
解释:
二叉查找树如下 :
10
/\
1 11
\ \
6 12
可以返回二叉查找树的中序遍历 [1, 6, 10, 11, 12]

样例 2:

输入:{2,1,3}
输出:[1,2,3]
解释:
二叉查找树如下 :
2
/ \
1 3
可以返回二叉查找树的中序遍历 [1,2,3]

挑战

额外空间复杂度是O(h),其中h是这棵树的高度

Super Star:使用O(1)的额外空间复杂度

"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None Example of iterate a tree:
iterator = BSTIterator(root)
while iterator.hasNext():
node = iterator.next()
do something for node
""" class BSTIterator:
"""
@param: root: The root of binary tree.
"""
def __init__(self, root):
# do intialization if necessary
self.q = []
self.node = root """
@return: True if there has next node, or false
"""
def hasNext(self, ):
# write your code here
return self.node or self.q """
@return: return next node
"""
def next(self, ):
# write your code here
while self.node or self.q:
if self.node:
self.q.append(self.node)
self.node = self.node.left
else:
cur_node = self.q.pop()
self.node = cur_node.right
return cur_node
return None

dfs 二叉树中序遍历迭代解法——求解BST中第k小元素的更多相关文章

  1. 图解中序遍历线索化二叉树,中序线索二叉树遍历,C\C++描述

    body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...

  2. LeetCode---105. 从前序与中序遍历序列构造二叉树 (Medium)

    题目:105. 从前序与中序遍历序列构造二叉树 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7 ...

  3. 【C++】根据二叉树的前序遍历和中序遍历重建二叉树并输出后续遍历

    /* 现在有一个问题,已知二叉树的前序遍历和中序遍历: PreOrder:GDAFEMHZ InOrder:ADEFGHMZ 我们如何还原这颗二叉树,并求出他的后序遍历 我们基于一个事实:中序遍历一定 ...

  4. LeetCode:94_Binary Tree Inorder Traversal | 二叉树中序遍历 | Medium

    题目:Binary Tree Inorder Traversal 二叉树的中序遍历,和前序.中序一样的处理方式,代码见下: struct TreeNode { int val; TreeNode* l ...

  5. 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  6. nyist 202 红黑树(二叉树中序遍历)

    旋转对中序遍历没有影响,直接中序输出即可. #include <iostream> #include <cstdio> using namespace std; int n; ...

  7. 二叉树系列 - 二叉搜索树 - [LeetCode] 中序遍历中利用 pre节点避免额外空间。题:Recover Binary Search Tree,Validate Binary Search Tree

    二叉搜索树是常用的概念,它的定义如下: The left subtree of a node contains only nodes with keys less than the node's ke ...

  8. 二叉树:前序遍历、中序遍历、后序遍历,BFS,DFS

    1.定义 一棵二叉树由根结点.左子树和右子树三部分组成,若规定 D.L.R 分别代表遍历根结点.遍历左子树.遍历右子树,则二叉树的遍历方式有 6 种:DLR.DRL.LDR.LRD.RDL.RLD.由 ...

  9. 【二叉树遍历模版】前序遍历&&中序遍历&&后序遍历&&层次遍历&&Root->Right->Left遍历

    [二叉树遍历模版]前序遍历     1.递归实现 test.cpp: 12345678910111213141516171819202122232425262728293031323334353637 ...

随机推荐

  1. 【医学】三分钟看懂乳腺BI-RADS分级

    “BI-RADS”是指美国放射学会的乳腺影像报告和数据系统(Breast Imaging Reporting and Data System)的缩写.BI-RADS分级法将乳腺病变分为0-6级,用来评 ...

  2. Expect Command And How To Automate Shell Scripts Like Magic

    In the previous post, we talked about writing practical shell scripts and we saw how it is easy to w ...

  3. how to write your first linux device driver

    how to write your first linux device driver 0. environment-ubuntu 1804 64bit 1. apt-get install linu ...

  4. something want to write

    1.时间戳不能相信是因为机器时间有误差.相当于机器不断电的跑着时钟. 2.写log的时候记得log别人的ip,不然没办法很好的debug.

  5. RuntimeError: Model class myapp.models.Test doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

    没有添加子应用在settings里面!

  6. 重学C语言之结构体

    概念 结构体是一种构造类型,由若干个成员组成,成员可以是基本数据类型,或是另一个结构体 声明结构体 struct 结构体名 { 成员列表 }; 结构体名表示结构的类型名. 声明一个结构体表示创建一种新 ...

  7. Python实现Newton和lagrange插值

    一.介绍Newton和lagrange插值:给出一组数据进行Newton和lagrange插值,同时将结果用plot呈现出来1.首先是Lagrange插值:根据插值的方法,先对每次的结果求积,在对结果 ...

  8. c#使用SoundPlayer播放wav格式音频

    1.引用System.Media名称空间下的类SoundPlayer   SoundPlayer player = new SoundPlayer(); 2.方法调用Play(); public vo ...

  9. Spring Web MVC框架简介

    Web MVC framework框架 Spring Web MVC框架简介 Spring MVC的核心是`DispatcherServlet`,该类作用非常多,分发请求处理,配置处理器映射,处理视图 ...

  10. Java之路---Day13

    2019-10-28-22:40:14 目录 1.Instanceof关键字 2.Final关键字 2.1Final关键字修饰类 2.2Final关键字修饰成员方法 2.3Final关键字修饰局部变量 ...