[LeetCode]230.Kth Smallest Element in a BST

160 篇文章 28 订阅

题目

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.

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个就终止遍历。

代码

/*---------------------------------------
*   日期:2015-08-03
*   作者:SJF0115
*   题目: 230.Kth Smallest Element in a BST
*   网址:https://leetcode.com/problems/kth-smallest-element-in-a-bst/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

struct TreeNode{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x),left(nullptr),right(nullptr){}
};

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        if(k <= 0 || root == nullptr){
            return -1;
        }//if
        int result = 0;
        int index = 0;
        InOrder(root,k,index,result);
        return result;
    }
private:
    void InOrder(TreeNode* root,int k,int &index,int &result){
        if(root){
            if(root->left){
                InOrder(root->left,k,index,result);
            }//if
            ++index;
            // 找到目标则不用遍历
            if(index > k){
                return;
            }//if
            // 找到目标
            if(index == k){
                result = root->val;
                return;
            }//if
            if(root->right){
                InOrder(root->right,k,index,result);
            }//if
        }//if
    }
};

int main(){
    Solution s;
    int k = 7;
    TreeNode *root = new TreeNode(5);
    TreeNode *node1 = new TreeNode(2);
    TreeNode *node2 = new TreeNode(3);
    TreeNode *node3 = new TreeNode(4);
    TreeNode *node4 = new TreeNode(9);
    TreeNode *node5 = new TreeNode(6);
    TreeNode *node6 = new TreeNode(7);
    TreeNode *node7 = new TreeNode(11);

    root->left = node2;
    root->right = node4;
    node2->left = node1;
    node2->right = node3;
    node4->left = node5;
    node4->right = node7;
    node5->right = node6;

    cout<<s.kthSmallest(root,k)<<endl;
    return 0;
}

运行时间

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值