首页 > 其他 > 详细

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

时间:2019-09-29 23:53:20      阅读:154      评论:0      收藏:0      [点我收藏+]

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
                
    

  

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

原文:https://www.cnblogs.com/bonelee/p/11610292.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!