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 ...
随机推荐
- JVM系列之二:编译过程
1. Java的编译和执行 编译包括两种情况: 1,源码编译成字节码2,字节码编译成本地机器码(符合本地系统专属的指令) 解释执行也包括两种情况: 1,源码解释执行2,字节码解释执行 解释和编译执行的 ...
- Hbase(一)了解Hbase与Phoenix
前言 HBase是一个分布式的.面向列的开源数据库,该技术来源于 Fay Chang 所撰写的Google论文“Bigtable:一个结构化数据的分布式存储系统”.就像Bigtable利用了Googl ...
- spark 基本操作(二)
1.dataframe 基本操作 def main(args: Array[String]): Unit = { val spark = SparkSession.builder() .appName ...
- winform 通用自动更新程序
通用自动更新程序 主要功能: 1. 可用于 C/S 程序的更新,集成到宿主主程序非常简单和配置非常简单,或不集成到主程序独立运行. 2. 支持 HTTP.FTP.WebService等多种更新下载方式 ...
- Python【每日一问】31
问: [基础题]:有 n 个人围成一圈,顺序排号.从第一个人开始报数(从 1 到 3 报数) ,凡报到 3 的人退出圈子,问最后留下的是原来第几号的那位. (n由键盘输入,比如n=100) [提高题] ...
- 使用Fiddler抓包、wireshark抓包分析(三次握手、四次挥手深入理解)
==================Fiddler抓包================== Fiddler支持代理的功能,也就是说你所有的http请求都可以通过它来转发,Fiddler代理默认使用端口 ...
- 算法:array1和array2地址值相同,都指向堆空间的唯一的一个数组实体(不是数组的复制)
package com.atguigu; public class fuzhi { public static void main(String[] args) { int[] array1=new ...
- 阿里云CentOS服务器下安装Golang1.13并配置代理
注:root账户或添加sudo命令运行. 下载到/usr/local位置并解压 cd /usr/local wget https://studygolang.com/dl/golang/go1.13. ...
- Spark Core知识点复习-2
day1112 1.spark core复习 任务提交 缓存 checkPoint 自定义排序 自定义分区器 自定义累加器 广播变量 Spark Shuffle过程 SparkSQL 一. Spark ...
- 『一维线性dp的四边形不等式优化』
四边形不等式 定义:设\(w(x,y)\)是定义在整数集合上的的二元函数,若对于定义域上的任意整数\(a,b,c,d\),在满足\(a\leq b\leq c \leq d\)时,都有\(w(a,d) ...