Kth Smallest Element in a BST - leetcode 230号题目个人题解

Kth Smallest Element in a BST - leetcode 230号题目个人题解


题目要求

Given a binary search tree, write a function kthSmallest to find the ***k***th smallest element in it.

Note:

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

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?

解题思路

这道题中,题目已经给出一个二叉搜索树,要我们在其中找到第k小的数字。

回想一下,之前我们做过找出一个数组中第k小的数的算法,用的是分治的思想。不过那是在数组中进行查找,而本题不能采用那种做法。

其实这道题目十分简单。既然已经给出了二叉搜索树,也就是说这棵树已经是有序的了,只要用中序的深度优先遍历的到的就是一个从小到大排好的数组。在这里我们不用遍历完所有的节点,因为只需要找到第k小的数字,那么只要在访问第k个节点的时候,把节点上的数字输出就好了。

对于树的深度优先遍历,可以用递归的方式实现。

详细代码

/**此处为树的实现方式
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        int count = 0;      //count是用于记录遍历到第几个节点的
        return dfs(root,k,count);
    }
    int dfs(TreeNode* n,int k,int& count){
        int ans;
        if(n->left!=NULL) ans = dfs(n->left,k,count);
        if(count == k) return ans;

        else count++;
        if(count == k) return n->val;

        if(n->right != NULL) ans = dfs(n->right,k,count);
        return ans;
    }
};

结语

写递归函数的时候一定要注意返回条件。


(完)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值