leetcode: Kth Smallest Element in a BST

本文深入探讨了在二叉搜索树(BST)中查找第k小节点的方法,介绍了两种主要的解法:利用BST性质进行递归查找以及深度优先搜索。详细解释了每种方法的原理、实现过程,并通过代码实例展示了具体实现,旨在帮助读者理解并掌握BST相关算法。

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

寻找BST中第k小的节点。

看了下,主流有两种解法。

1. 利用BST的特性:若节点n有i个左子结点,则其一定是第i+1小的节点。我们不妨加一个方法countNum(Node)来计算Node和其所有子节点的数量从而确定Node父节点的大小,通过比较判断第k个节点在左侧还是右侧,不断逼近。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        int num = countNum(root.left);
        if(k<=num)
        {
            return kthSmallest(root.left,k);
        }
        else if(k==num+1)
        {
            return root.val;
        }
        else
        {
            return kthSmallest(root.right,k-num-1);
        }
    }
    static int countNum(TreeNode t)
    {
        if(t==null)
        {
            return 0;
        }
        return 1+countNum(t.left)+countNum(t.right);
    }
}
时间为496 ms


2. 深搜

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    static int count,rt;
    public int kthSmallest(TreeNode root, int k) {
       count = k;
       rt=0;
       DP(root,k);
       return rt;
    }
    
    static void DP(TreeNode n,int k)
    {
        if(n.left != null)
        {
            DP(n.left,k);
        }
        count--;
        if(count==0)
        {
            rt = n.val;
            return ;
        }
        if(n.right != null)
        {
            DP(n.right,k);
        }
    }
}
耗时
396 ms



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值