Kth Smallest Element in a BST

本文介绍了一种寻找二叉搜索树中第k个最小元素的方法,通过中序遍历二叉搜索树获得有序节点值列表,进而找到目标元素。文章提供了具体的Java实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

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

Example 2:

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

Tags: Binary Search

解读题意

找出二叉搜索树中第k个大的元素

思路1

这是一道典型的二叉搜索树遍历问题。对二叉搜索树进行中序遍历可以得到有序的数组,访问其对应元素即可。

public class Solution {

    private int count = 0;
    private int kth = 0;

    public int kthSmallest(TreeNode root, int k) {

        if (root == null || k <= 0)
            return 0;

        // BST中序遍历得到有序列表
        midOrder(root,k);

        return kth;
    }

    private void midOrder(TreeNode root, int k) {

        if (root == null)
            return;

        midOrder(root.left, k);
        count++;
        if (k == count)
            kth = root.val;
        midOrder(root.right, k);
    }
}
  • time complexity:O(n)。

leetCode汇总:https://blog.csdn.net/qingtian_1993/article/details/80588941

项目源码,欢迎star:https://github.com/mcrwayfun/java-leet-code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值