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. ddns+ros(routeros)+centos7.6+nginx+php+dnspod

    参考文章: http://www.myxzy.com/post-464.html https://www.cnblogs.com/crazytata/p/9686490.html php的源码下载: ...

  2. java利用注解及反射做通用的入参校验

    一.原理: 1.做一个field注解,注解有两个参数:是否必填.toString之后的最大长度 2.对某个request类(或基类),使用注解标记某个字段的校验详情 3.通用的static方法,利用反 ...

  3. ASP.NET Core WebApi基于Redis实现Token接口安全认证

    一.课程介绍 明人不说暗话,跟着阿笨一起玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NET WebSer ...

  4. PS 个人常用功能

    PS是什么? Adobe Photoshop,简称"PS",是由Adobe Systems开发和发行的图像处理软件. 不是美工,为什么要学PS? 1)写博客时,有些需要的素材图片有 ...

  5. spring boot 从开发到部署上线(简明版)

    我们组有一个优良传统--借鉴于"冰桶挑战赛"的形式,采取点名的方式,促进团队成员每天利用一小段时间,不断的完善团队 wiki 的小游戏. 但有时候忙于业务,可能会忘记,所以我写了一 ...

  6. MySQL常见的应用异常记录

    >>Error Code: 1045. Access denied for user 'test'@'%' (using password: YES) 使用MySQL的select * i ...

  7. react 父组件调用子组件方法、子组件调用父组件方法

    我们闲话不多说,直接上代码 // 父组件 import React, {Component} from 'react'; class Parents extends Component { const ...

  8. Spring JPA事务

    目录 1. 概述 促进阅读: 2. 配置不带XML的事务 3. 使用XML配置事务 4. @Transactional 注解 5. 潜在的陷阱 5.1. 事务和代理 5.2. 更改隔离级别 5.3. ...

  9. SetWindowLong函数GetWindowLong函数

    这两个函数具体应用如下:SetWindowLong函数GetWindowLong函数 Delphi窗口化游戏 var Thwnd:HWND;//声明变量 句柄变量 devmodel1:DEVMODE; ...

  10. swiper4基础

    这段时间在公司实习做前端,感觉前端没学习到很多前端框架,接口那些都是写好的,只需要调用就好,感觉没什么好记的,唯一觉得有必要记的就是swiper轮播了,在前端做网站的时候经常用到swiper做公告,图 ...