首页 > 其他分享 >dfs 二叉树中序遍历迭代解法——求解BST中第k小元素

dfs 二叉树中序遍历迭代解法——求解BST中第k小元素

时间:2023-05-31 10:32:53浏览次数:51  
标签:node return val BST 中序 pNode 二叉树 root self

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

 

标签:node,return,val,BST,中序,pNode,二叉树,root,self
From: https://blog.51cto.com/u_11908275/6384768

相关文章

  • Efficient Correction of Single InsertionlDeletion and Multi-Substitution Errors
    EfficientCorrectionofSingleInsertionlDeletionandMulti-SubstitutionErrorsG.J.Han,Y.L.Guan,K.Cai,K.S.Chan,andL.J.KongA!JshYlc�Atwo-stagesynchronizationalgorithmisproposedtocorrectsingleinsertion/deletionandmulti-substitution......
  • 区块链的技术——账本是去中心化的分布式存储,加密+校验(哈希二叉树)+多数选举来防止篡改
    ......
  • 算法 dfs —— 将二叉树 先序遍历 转为 链表
    将二叉树拆成链表中文English将一棵二叉树按照前序遍历拆解成为一个 假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。Example样例1:输入:{1,2,5,3,4,#,6}输出:{1,#,2,#,3,#,4,#,5,#,6}解释:1/\25/\\3461\2......
  • 算法 dfs 二叉树的所有路径
    480. 二叉树的所有路径给一棵二叉树,找出从根节点到叶子节点的所有路径。Example样例1:输入:{1,2,3,#,5}输出:["1->2->5","1->3"]解释:1/\23\5样例2:输入:{1,2}输出:["1->2"]解释:1/2"""DefinitionofTreeNode:classTree......
  • 算法 翻转二叉树 dfs
    翻转二叉树翻转一棵二叉树。左右子树交换。Example样例1:输入:{1,3,#}输出:{1,#,3}解释: 11 /=>\ 33样例2:输入:{1,2,3,#,#,4}输出:{1,3,2,#,4}解释: 11/\/\23=>32/\4......
  • 算法——dfs 判断是否为BST
    95. 验证二叉查找树中文English给定一个二叉树,判断它是否是合法的二叉查找树(BST)一棵BST定义为:节点的左子树中的值要严格小于该节点的值。节点的右子树中的值要严格大于该节点的值。左右子树也必须是二叉查找树。一个节点的树也是二叉查找树。Example样例1:输入:{-1}输出:true解......
  • Abstract Factory Pattern 抽象工厂模式简介与 C# 示例【创建型】【设计模式来了】
    〇、简介1、什么是抽象工厂模式?一句话解释:  通过对抽象类和抽象工厂的一组实现,独立出一系列新的操作,客户端无需了解其逻辑直接访问。抽象工厂模式(AbstractFactoryPattern)是一种创建型模式。它用于创建一组相关对象的家族。强调的是一组对象之间的协作关系,而不是单个对象之......
  • 二叉树已知前中序,求后序
    [USACO3.4]美国血统AmericanHeritage题目描述农夫约翰非常认真地对待他的奶牛们的血统。然而他不是一个真正优秀的记帐员。他把他的奶牛们的家谱作成二叉树,并且把二叉树以更线性的“树的中序遍历”和“树的前序遍历”的符号加以记录而不是用图形的方法。你的任务是在被给......
  • 打印树形结构(可视化二叉树)
    平时开发时,偶尔会操作二叉树,而查看二叉树的结构,是一种比较费时的事情,我们可以把它按照本身的结构打印出来,从而方便查看。例如Nodea=newNode(110);Nodeb=newNode(105);Nodec=newNode(115);Noded=newNode(102);Node......
  • ImportError: /lib64/libstdc++.so.6: version `CXXABI_1.3.8' not found
    [root@localhostPaddleOCR]#strings/lib64/libstdc++.so.6|grep'CXXABI'CXXABI_1.3CXXABI_1.3.1CXXABI_1.3.2CXXABI_1.3.3CXXABI_1.3.4CXXABI_1.3.5CXXABI_1.3.6CXXABI_1.3.7CXXABI_TM_1[root@localhostPaddleOCR]#find/-name"libstdc++.......