dfs binary tree traversal sequence iterative solution - solving BST small element in the k

BST small element of the first K

Chinese English

To a binary search tree, write a  KthSmallest function to find the first of which K smaller elements.

Example

Example 1:

输入:{1,#,2},2
输出:2
解释:
	1
	 \
	  2
第二小的元素是2。

Sample 2:

输入:{2,1,3},1
输出:1
解释:
  2
 / \
1   3
第一小的元素是1。

Challenge

If the tree is modified often BST (insertion / deletion) and you need to very quickly find the K smaller elements of it? How would you optimize this KthSmallest function?

Notice

You may assume that k always effective  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
                
    

  

Guess you like

Origin www.cnblogs.com/bonelee/p/11610292.html