LeetCode-230. Kth Smallest Element in a BST

本文介绍了一种利用中序遍历方法在二叉查找树中寻找第K小元素的有效算法。通过递归地访问左子树、根节点和右子树,可以确保按升序访问所有节点。当计数等于K时,当前节点的值即为所求。

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

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.

题意:从二叉查找树中找第k小的数。

思路:中序遍历,找到第k个便是。

C++:

class Solution {
public:
    int num=0;//记录次数
int re;//记录最终结果

//中序遍历的方法
void digui(TreeNode* root, int k)
{
    if(root->left!=NULL)
        digui(root->left,k);
    num++;
    if(num==k)
        re=root->val;
    if(root->right!=NULL)
        digui(root->right,k);
    return;
}
    int kthSmallest(TreeNode* root, int k) {
        digui(root,k);
    return re;
    }
};

LeetCode很奇怪,同样的代码Java却过不了。。。还是1 null 2 ,2这个数据过不了,我自己测试的都能过。。。。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public static int cnt = 0;
    public static int ans;
    public int kthSmallest(TreeNode root, int k) {
        travels(root, k);
        return ans;
    }
    public void travels(TreeNode node, int k) {
        if(node.left != null)
            travels(node.left, k);
        cnt ++;
        if(cnt == k) {
            ans = node.val;
        }
        if(node.right != null)
            travels(node.right, k);
    }
}

更新----------------

终于找到原因了,原来我用了静态变量,后台测试连续调用,结果不清零。。。

最终Java代码:

/**
 * 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 cnt = 0;
    public int ans;
    public int kthSmallest(TreeNode root, int k) {
        travels(root, k);
        return ans;
    }
    public void travels(TreeNode node, int k) {
        if(node == null)
            return ;
        travels(node.left, k);
        cnt ++;
        if(cnt == k) {
            ans = node.val;
            return ;
        }
        travels(node.right, k);
    }
}

 

转载于:https://www.cnblogs.com/wxisme/p/5202393.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值