zoukankan      html  css  js  c++  java
  • LeetCode-230. Kth Smallest Element in a BST

    https://leetcode.com/problems/kth-smallest-element-in-a-bst/

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

    Note:
    You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

    Follow up:
    What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

    Hint:

    1.Try to utilize the property of a BST.
    2.What if you could modify the BST node's structure?
    3.The optimal runtime complexity is O(height of BST).

    Solution

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def kthSmallest(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: int
            
            count = self.countNode(root.left)
            if k <= count:
                return self.kthSmallest(root.left, k)
            elif k > count + 1:
                return self.kthSmallest(root.right, k-count-1)
            return root.val
            
        def countNode(self, node):
            if node == None:
                return 0
            return 1 + self.countNode(node.left) + self.countNode(node.right)
        """
            st = []
            while root is not None:
                st.append(root)
                root = root.left
            while k != 0:
                node = st.pop()
                print(node.val)
                k -= 1
                if k == 0:
                    return node.val
                right = node.right
                while right:
                    st.append(right)
                    right = right.left
            return -1
    
  • 相关阅读:
    中山游记
    半僧
    脾气
    当奶猫来敲门
    《易经》初识
    读《动物农庄》
    update layer tree导致页面卡顿
    读《解忧杂货店》
    看小说与写小说
    做程序员的这五年
  • 原文地址:https://www.cnblogs.com/binwone/p/6052484.html
Copyright © 2011-2022 走看看