zoukankan      html  css  js  c++  java
  • leetcode刷题笔记 230题 二叉搜索树中第K小的元素

    leetcode刷题笔记 230题 二叉搜索树中第K小的元素

    源地址:230. 二叉搜索树中第K小的元素

    问题描述:

    给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

    说明:
    你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

    示例 1:

    输入: root = [3,1,4,null,2], k = 1
    3
    /
    1 4

    2
    输出: 1
    示例 2:

    输入: root = [5,3,6,2,4,null,null,1], k = 3
    5
    /
    3 6
    /
    2 4
    /
    1
    输出: 3
    进阶:
    如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?

    //将问题转化为中序遍历中的第K个元素
    //可以分为递归与迭代两种思路
    //递归
    /**
     * Definition for a binary tree node.
     * class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
     *   var value: Int = _value
     *   var left: TreeNode = _left
     *   var right: TreeNode = _right
     * }
     */
    import scala.collection.mutable
    object Solution {
        def kthSmallest(root: TreeNode, k: Int): Int = {
            val res = new mutable.ListBuffer[Int]()
            def inorder(root: TreeNode): Unit = {
                if (root == null) return
                if (root.left != null) inorder(root.left)
                res.append(root.value)
                if (root.right != null) inorder(root.right)
            }
            inorder(root)
            println(res.mkString(" "))
            return res(k-1)
        }
    }
    //迭代
    object Solution {
        def kthSmallest(root: TreeNode, k: Int): Int = {
            
            val stack = collection.mutable.Stack[TreeNode]()
            var node = root
            var counter = 0
            
            
            while(node != null || stack.nonEmpty) {
                while(node != null) {
                    stack.push(node)
                    node = node.left
                }
                node = stack.pop
                counter += 1
                if(counter == k) return node.value
                else node = node.right
                
            }
            return -1
        }
    }
    
  • 相关阅读:
    es6数组方法
    es5数组方法
    es6中的generator函数
    async、await
    CSS---文本属性及其属性值
    MySQL---查询某个字段内容中存不存在某个数据,与like不同(FIND_IN_SET(str,strlist))
    CSS---background属性及其属性值
    TP---时间查询(当日、本周、本月、本年)
    PHP---各种输出详解
    type=“text”只能输入数字!
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13830339.html
Copyright © 2011-2022 走看看