• 230. Kth Smallest Element in a BST


    package LeetCode_230
    import java.util.*
    /**
     * 230. Kth Smallest Element in a BST
     * https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
     *
     * Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
     *
    Example 1:
    Input: root = [3,1,4,null,2], k = 1
      3
     / 
    1   4
     
      2
    Output: 1
    
    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?
    
    Constraints:
    1. The number of elements of the BST is between 1 to 10^4.
    2. You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
     * */
    class TreeNode(var `val`: Int){
        var left: TreeNode?=null
        var right: TreeNode?=null
    }
    class Solution {
        /*
        * solution: traverse tree via inorder and check the index, because its sorted after inorder
        * Time complexity:O(n), Space complexity:O(n)
        * */
        fun kthSmallest(root_: TreeNode?, k: Int): Int {
            var root = root_
            val stack = Stack<TreeNode>()
            var count = 0
            //inorder to find result
            while (stack.isNotEmpty() || root!=null){
                if (root!=null){
                    stack.push(root)
                    root = root.left
                } else {
                    root = stack.pop()
                    count++
                    if (count==k){
                        return root.`val`
                    }
                    root = root.right
                }
            }
            return 0
        }
    }
  • 相关阅读:
    学生数据增删改查--顺序表
    应用3+2mvc第一次作业
    双色球随机选【代码】
    字符串穷举
    使用nuget发布自己的包
    VS CODE中配置JAVA格式化细节
    反射的理解(含一点xml)
    UdpClient实现udp消息收发
    c#背包问题代码
    利用TcpClient,简单的tcp消息收发
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13417333.html
Copyright © 2020-2023  润新知