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 ...
随机推荐
- Linux笔记本合上屏幕不待机
Linux笔记本合上屏幕不待机[]# vim /etc/systemd/logind.conf# This file is part of systemd.## systemd is free sof ...
- [HeadFrist-HTMLCSS学习笔记]第三章构建模块:Web页面建设
[HeadFrist-HTMLCSS学习笔记]第三章构建模块:Web页面建设 敲黑板!! <q>元素添加短引用,<blockquote>添加长引用 在段落里添加引用就使用< ...
- 《Linux就该这么学》培训笔记_ch18_使用MariaDB数据库管理系统
<Linux就该这么学>培训笔记_ch18_使用MariaDB数据库管理系统 文章最后会post上书本的笔记照片. 文章主要内容: 初始化MariaDB服务 管理用户以及授权 创建数据库与 ...
- cad.net 获取所有已经安装的cad版本信息
计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Autodesk\Hardcopy var ackey = Registry.LocalMachine.OpenSubKey(@&quo ...
- CountDownLatch源码
public class CountDownLatchExample1 { public static void main(String[] args) throws Exception { Exec ...
- 25个led灯新玩法
Microbit板子的25个led灯,是5X5的阵列,led(lights emitting diodes)中文叫发光二极管,有单向导电性,还发光,有各种颜色的,红,蓝,黄等等.mPython可以让你 ...
- Faiss的学习和入门文章
可以看这里的文章: https://www.leiphone.com/news/201703/84gDbSOgJcxiC3DW.html https://waltyou.github.io/Faiss ...
- 043 用户注册功能03--Redis安装及完成短信发送功能
1.Redis安装 (1)下载地址:https://github.com/MicrosoftArchive/redis/releases/tag/win-3.2.100 ( redis官网: ht ...
- Luogu - P1018 乘积最大 - 题解
原文:https://www.luogu.org/problemnew/solution/P1018?page=7 题目:P1018[乘积最大] 前言: 这题的正解理论上说是DP,可是由于民间数据太水 ...
- Android工具使用之UiAutomatorViewer
学习博客: https://blog.csdn.net/l403040463/article/details/79235670 使用, 添加web 网页的监控.