• 作者: 负雪明烛
  • id: fuxuemingzhu
  • 个人博客: http://fuxuemingzhu.cn/
  • 公众号:负雪明烛
  • 本文关键词:算法题,刷题,Leetcode, 力扣,二叉搜索树,BST,第 k 小的元素,Python, C++, Java

题目地址: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.

Note:

  • You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

Example 1:

  1. Input: root = [3,1,4,null,2], k = 1
  2. 3
  3. / \
  4. 1 4
  5. \
  6. 2
  7. Output: 1

Example 2:

  1. Input: root = [5,3,6,2,4,null,null,1], k = 3
  2. 5
  3. / \
  4. 3 6
  5. / \
  6. 2 4
  7. /
  8. 1
  9. Output: 3

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?

题目大意

找出一个BST中第K小的数字是多少。

解题方法

各位题友大家好! 我是负雪明烛。

今天题目重点只有一个:二叉搜索树(BST)。

遇到二叉搜索树,立刻想到这句话:

二叉搜索树(BST)的中序遍历是有序的」。

这是解决所有二叉搜索树问题的关键。

题目要求 BST 中第 k 小的元素,等价于求 BST 中序遍历的第 k 个元素。

分享二叉树遍历的模板:先序、中序、后序遍历方式的区别在于把「执行操作」放在两个递归函数的位置。

伪代码在下面。

  1. 先序遍历:
  1. def dfs(root):
  2. if not root:
  3. return
  4. 执行操作
  5. dfs(root.left)
  6. dfs(root.right)
  1. 中序遍历:
  1. def dfs(root):
  2. if not root:
  3. return
  4. dfs(root.left)
  5. 执行操作
  6. dfs(root.right)
  1. 后序遍历:
  1. def dfs(root):
  2. if not root:
  3. return
  4. dfs(root.left)
  5. dfs(root.right)
  6. 执行操作

本题是使用了中序遍历,所以把「执行操作」这一步改成自己想要的代码。

于是有了下面两种写法。

方法一:数组保存中序遍历结果

这个方法是最直观的,也最不容易出错的。

  1. 先中序遍历,把结果放在数组中;
  2. 最后返回数组的第 k 个元素。

对应的代码如下,二叉树的各种遍历方式是基本功,务必要掌握。

Java 代码如下:

  1. public class Solution {
  2. List<Integer> list;
  3. public int kthSmallest(TreeNode root, int k) {
  4. list = new ArrayList<Integer>();
  5. dfs(root);
  6. return list.get(k - 1);
  7. }
  8. public void dfs(TreeNode root){
  9. if(root == null){
  10. return;
  11. }
  12. dfs(root.left);
  13. list.add(root.val);
  14. dfs(root.right);
  15. }
  16. }

C++ 代码如下:

  1. class Solution {
  2. public:
  3. int kthSmallest(TreeNode* root, int k) {
  4. vector<int> res;
  5. dfs(root, res);
  6. return res[k - 1];
  7. }
  8. void dfs(TreeNode* root, vector<int>& res) {
  9. if (!root) return;
  10. dfs(root->left, res);
  11. res.push_back(root->val);
  12. dfs(root->right, res);
  13. }
  14. };

Python 语言如下:

  1. class Solution(object):
  2. def kthSmallest(self, root, k):
  3. res = []
  4. self.dfs(root, res)
  5. return res[k - 1]
  6. def dfs(self, root, res):
  7. if not root: return
  8. self.dfs(root.left, res)
  9. res.append(root.val)
  10. self.dfs(root.right, res)

复杂度分析:

  • 时间复杂度:

    O

    (

    N

    )

    O(N)

    O(N),因为每个节点只访问了一次;

  • 空间复杂度:

    O

    (

    N

    )

    O(N)

    O(N),因为需要数组保存二叉树的每个节点值。

方法二:只保存第 k 个节点

在方法一中,我们保存了整个中序遍历数组,比较浪费空间。

其实我们只需要知道,在中序遍历的时候,第 k 个被访问的节点即可。访问到第 k 个节点后,递归终止,后面的节点就不用访问了。

下图展示了中序遍历过程中的节点访问顺序。

具体的做法中,我们需要需要两个变量:

  1. 用一个全局变量保存最终的结果;
  2. 用一个全局变量保存当前访问到第几个节点。

如果不使用全局变量,而是使用函数传参,需要注意「值传递」和「引用传递」的区别:

值传递:每个递归的内部都需要对同一个变量修改,如果用普通函数的传参,对于 int 型的参数,使用的是值传递,即拷贝了一份传到了函数里面。那么函数里面对 int 型的修改不会影响外边的变量。

使用全局变量,可以保证递归函数的每次修改都是反映到全局的,从而保证遍历到第 k 个的时候,所有的递归立刻停止。

Java 代码如下:

  1. public class Solution {
  2. int res;
  3. int count;
  4. public int kthSmallest(TreeNode root, int k) {
  5. res = 0;
  6. count = k;
  7. dfs(root);
  8. return res;
  9. }
  10. public void dfs(TreeNode root){
  11. if(root == null){
  12. return;
  13. }
  14. dfs(root.left);
  15. count--;
  16. if(count == 0){
  17. res = root.val;
  18. return;
  19. }
  20. dfs(root.right);
  21. }
  22. }

C++ 代码如下:

  1. class Solution {
  2. public:
  3. int kthSmallest(TreeNode* root, int k) {
  4. count = k;
  5. dfs(root);
  6. return res;
  7. }
  8. void dfs(TreeNode* root) {
  9. if (!root) return;
  10. dfs(root->left);
  11. count -= 1;
  12. if (count == 0) {
  13. res = root->val;
  14. return;
  15. }
  16. dfs(root->right);
  17. }
  18. private:
  19. int res;
  20. int count;
  21. };

Python 代码如下:

  1. class Solution(object):
  2. def kthSmallest(self, root, k):
  3. self.res = 0
  4. self.count = k
  5. self.dfs(root)
  6. return self.res
  7. def dfs(self, root):
  8. if not root: return
  9. self.dfs(root.left)
  10. self.count -= 1
  11. if self.count == 0:
  12. self.res = root.val
  13. return
  14. self.dfs(root.right)

复杂度分析:

  • 时间复杂度:

    O

    (

    k

    )

    O(k)

    O(k),因为只访问了前

    k

    k

    k 个节点;

  • 空间复杂度:

    O

    (

    h

    )

    O(h)

    O(h),其中

    h

    h

    h 为树的高度,因为递归用了系统栈,而栈的深度最多只有树的高度。

迭代

待补。

总结

  1. 二叉树的多种遍历方式必须要掌握。
  2. 一定切记:二叉搜索树的中序遍历是有序的。
  3. 另外建议刚开始刷题的朋友,不妨从二叉树上手。

类似题目:


我是 @负雪明烛 ,刷算法题 1000 多道,写了 1000 多篇算法题解,收获阅读量 300 万。

关注我,你将不会错过我的精彩动画题解、面试题分享、组队刷题活动,进入主页 @负雪明烛 右侧有刷题组织,从此刷题不再孤单。

日期

2017 年 4 月 10 日
2019 年 1 月 25 日 —— 这学期最后一个工作日
2021 年 10 月 17 日

【LeetCode】230. 二叉搜索树中第K小的元素 Kth Smallest Element in a BST的更多相关文章

  1. LeetCode 230. 二叉搜索树中第K小的元素(Kth Smallest Element in a BST)

    230. 二叉搜索树中第K小的元素 230. Kth Smallest Element in a BST 题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的 ...

  2. [Swift]LeetCode230. 二叉搜索树中第K小的元素 | Kth Smallest Element in a BST

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

  3. Java实现 LeetCode 230 二叉搜索树中第K小的元素

    230. 二叉搜索树中第K小的元素 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 说明: 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数. ...

  4. [LeetCode]230. 二叉搜索树中第K小的元素(BST)(中序遍历)、530. 二叉搜索树的最小绝对差(BST)(中序遍历)

    题目230. 二叉搜索树中第K小的元素 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 题解 中序遍历BST,得到有序序列,返回有序序列的k-1号元素. 代 ...

  5. LeetCode——230. 二叉搜索树中第K小的元素

    给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 说明: 你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数. 示例 1: 输入: root = ...

  6. leetcode 230 二叉搜索树中第K小的元素

    方法1:统计每个节点的子节点数目,当k>左子树节点数目时向左子树搜索,k=左子树节点数目时返回根节点,否则向右子树搜索. 方法2:递归中序遍历,这里开了O(n)空间的数组. class Solu ...

  7. LeetCode 230. 二叉搜索树中第K小的元素(Kth Smallest Element in a BST)

    题目描述 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 说明:你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数. 示例 1: 输入: roo ...

  8. leetcode 230. 二叉搜索树中第K小的元素(C++)

    给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素. 说明:你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数. 示例 1: 输入: root = [ ...

  9. leetcode 230二叉搜索树中第k小的元素

    通过stack进行中序遍历迭代,timeO(k),spaceO(1) /** * Definition for a binary tree node. * struct TreeNode { * in ...

随机推荐

  1. java数组中Arrays类

    使用Arrays类之后要先导入包,即在开头添加这行: import.java.util.Arrays 1,排序:Arrays.sort(数组名) 排序后为数组升序. 2,将数组转换成字符串:Array ...

  2. 搭建简单的SpringCloud项目二:服务层和消费层

    GitHub:https://github.com/ownzyuan/test-cloud 前篇:搭建简单的SpringCloud项目一:注册中心和公共层 后篇:搭建简单的SpringCloud项目三 ...

  3. Spring Security 基于URL的权限判断

    1.  FilterSecurityInterceptor 源码阅读 org.springframework.security.web.access.intercept.FilterSecurityI ...

  4. 1小时学会Git玩转GitHub

    版权声明:原创不易,本文禁止抄袭.转载,侵权必究! 本次教程建议一边阅读一边用电脑实操 目录 一.了解Git和Github 1.1 什么是Git 1.2 什么是版本控制系统 1.3 什么是Github ...

  5. Go知识盲区--闭包

    1. 引言 关于闭包的说明,曾在很多篇幅中都有过一些说明,包括Go基础--函数2, go 函数进阶,异常与错误 都有所提到, 但是会发现,好像原理(理论)都懂,但是就是不知道如何使用,或者在看到一些源 ...

  6. VIM中把^M替换为真正的换行符

    :%s/\r/\r/g 或者:%s/^M/\r/g 红色的^M不是直接打出,而是按住ctrl再依次按下V和M

  7. JmxTest

    package mbeanTest; import java.util.Set; import javax.management.Attribute; import javax.management. ...

  8. Activity 详解

    1.活动的生命周期 1.1.返回栈 Android是使用任务(Task)来管理活动的,一个任务就是一组存放在栈里的活动的集合,这个栈也被称作返回栈.栈是一种先进后出的数据结构,在默认情况下,每当我们启 ...

  9. Linux:sqlplus

    [oracle@hb shell_test]$ cat echo_time #!/bin/sh 一.最简单的调用sqlplus sqlplus -S "sys/unimas as sysdb ...

  10. Spring boot 配置文件默认放置位置,和加载优先级

    一 .默认配置文件目录 spring boot 启动会扫描以下位置的application.properties 或者application.yml文件作为spring boot 的默认配置文件 ,加 ...