dfs 二叉树中序遍历迭代解法——求解BST中第k小元素
BST中第K小的元素
给一棵二叉搜索树,写一个 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. 二叉查找树迭代器
设计实现一个带有下列属性的二叉查找树的迭代器:
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小元素的更多相关文章
- 图解中序遍历线索化二叉树,中序线索二叉树遍历,C\C++描述
body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...
- LeetCode---105. 从前序与中序遍历序列构造二叉树 (Medium)
题目:105. 从前序与中序遍历序列构造二叉树 根据一棵树的前序遍历与中序遍历构造二叉树. 注意: 你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7 ...
- 【C++】根据二叉树的前序遍历和中序遍历重建二叉树并输出后续遍历
/* 现在有一个问题,已知二叉树的前序遍历和中序遍历: PreOrder:GDAFEMHZ InOrder:ADEFGHMZ 我们如何还原这颗二叉树,并求出他的后序遍历 我们基于一个事实:中序遍历一定 ...
- LeetCode:94_Binary Tree Inorder Traversal | 二叉树中序遍历 | Medium
题目:Binary Tree Inorder Traversal 二叉树的中序遍历,和前序.中序一样的处理方式,代码见下: struct TreeNode { int val; TreeNode* l ...
- 【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...
- nyist 202 红黑树(二叉树中序遍历)
旋转对中序遍历没有影响,直接中序输出即可. #include <iostream> #include <cstdio> using namespace std; int n; ...
- 二叉树系列 - 二叉搜索树 - [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 ...
- 二叉树:前序遍历、中序遍历、后序遍历,BFS,DFS
1.定义 一棵二叉树由根结点.左子树和右子树三部分组成,若规定 D.L.R 分别代表遍历根结点.遍历左子树.遍历右子树,则二叉树的遍历方式有 6 种:DLR.DRL.LDR.LRD.RDL.RLD.由 ...
- 【二叉树遍历模版】前序遍历&&中序遍历&&后序遍历&&层次遍历&&Root->Right->Left遍历
[二叉树遍历模版]前序遍历 1.递归实现 test.cpp: 12345678910111213141516171819202122232425262728293031323334353637 ...
随机推荐
- java 压缩图片(只缩小体积,不更改图片尺寸)
1.情景展示 在调用腾讯身份证OCR接口的时候,由于要求图片大小只能限制在1MB以内,这样,就必须使用到图片压缩技术 2.代码展示 /** * 图片处理工具类 * @explain * @auth ...
- 超强在线考试系统源码(私有部署&二次开发)
随着信息化技术的发展,考试系统也在进行着深入的变革.从传统的纸质考试人工评分到现在的在线考试自动评分. 在线考试系统的应用场景也在逐渐扩宽,例如:学校的学生考试.员工培训考试.招聘考试.职称考试等等. ...
- List中的ArrayList和LinkedList源码分析
List是在面试中经常会问的一点,在我们面试中知道的仅仅是List是单列集合Collection下的一个实现类, List的实现接口又有几个,一个是ArrayList,还有一个是LinkedLis ...
- 使用vue搭建应用三引入scss
Css.Sass.Scss的含义及区别 Css(Cascading Style Sheets) 层叠样式表 Sass(Syntactically Awesome StyleSheets) 是一款强化 ...
- 高度随每片内容的高度变化的swiper react-native-unfixed-height-swiper
高度随每片内容的高度变化的swiper react-native-unfixed-height-swiper 内容可以文本 图片 视频 本例里面的为文本 使用方式1. npm i react-n ...
- 一文让你彻底理解准确率,精准率,召回率,真正率,假正率,ROC/AUC
参考资料:https://zhuanlan.zhihu.com/p/46714763 ROC/AUC作为机器学习的评估指标非常重要,也是面试中经常出现的问题(80%都会问到).其实,理解它并不是非常难 ...
- Java安装 --- jdk 和eclipse tomcat
本文主要使用win7进行安装 安装jdk jdk: 这里面有四个版本78910,会持续增加 链接:https://pan.baidu.com/s/1LTauKbBJKQVOvlbHx2dTwQ提取 ...
- 【题解】Luogu P5327 [ZJOI2019]语言
原题传送门 看到这种树上统计点对个数的题一般是线段树合并,这题也不出意外 先对这棵树进行树剖,对于每次普及语言,在\(x,y\)两点的线段树上的\(x,y\)两位置打\(+1\)标记,在点\(fa[l ...
- 【在 Nervos CKB 上做开发】Nervos CKB 脚本编程简介[5]:调试 debug
作者:Xuejie 原文链接:https://xuejie.space/2019_10_18_introduction_to_ckb_script_programming_debugging/ Ner ...
- "类"的讲稿
-----------------------面向对象基础------------------------------------方法(函数) { (c#p10为主,p27;javap96)+资料,讲 ...