Kth Smallest Element in a BST

25 篇文章 0 订阅

题目

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

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

思路

对搜索二叉树(BST)进行中序遍历, 得到便是有序的序列.
既可以把中序遍历的序列用数组来保存, 返回array[k-1]即可, 
但是空间复杂度为O(N), N为节点数.
也可以在中序遍历的过程中直接返回k-th小的数, 如代码中`method 2`.

code

/**
 * 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:
    void inorder(const TreeNode* root, vector<int>& arr) {
        if(root == NULL) return;

        inorder(root->left, arr);
        arr.push_back(root->val);
        inorder(root->right, arr);
    }

    void inorder(const TreeNode* root, const int k, int& res, int& c) {
        if(c == -1) return;
        if(root == NULL) {
            c++;
            return;
        }

        inorder(root->left, k, res, c);
        if(c == k) {
            res = root->val;
            c = -1;
            return;
        }
        inorder(root->right, k, res, c);
    }

    int kthSmallest(TreeNode* root, int k) {
        /// method 1
        // vector<int> arr;
        // inorder(root, arr);
        // return arr[k - 1];

        /// method 2
        int c = 0, res;
        inorder(root, k, res, c);
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值