首页 技术 正文
技术 2022年11月13日
0 收藏 559 点赞 3,228 浏览 1289 个字

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?

Hint:

    1. Try to utilize the property of a BST.
    2. What if you could modify the BST node’s structure?
    3. The optimal runtime complexity is O(height of BST).

题目意思:

  给定一棵二叉搜索树,找到第k小的元素

  注意:

    1、利用二叉搜索树的特性

    2、修改二叉搜索树的节点结构

    3、最优时间复杂度是0(树的高度)

解题思路:

方法一:

  二叉搜索树的特性:其中序遍历是有序的。故中序遍历访问,访问第k个元素即可。

Leetcode  Kth Smallest Element in a BST

方法二:

  利用分冶的方法。

  • 统计根节点左子树的节点个数cnt
  • 如果cnt+1 = k,则根节点即为第k个最小元素
  • 如果cnt+1 > k,则第k个最小元素在左子树,root = root->left;
  • 如果cnt+1 < k,则第k个最小元素在右子树,root = root->right;
  • 重复第一步

源代码:

方法一:

 class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> nodeStack;
if(root == NULL) return -;
while(true){
while(root){
nodeStack.push(root);
root = root->left;
}
TreeNode* node = nodeStack.top(); nodeStack.pop();
if(k == ) return node->val;
else root = node->right,k--;
}
}
};

方法二:

 class Solution {
public:
int calcNodeSize(TreeNode* root){
if( root == NULL) return ;
return + calcNodeSize(root->left) + calcNodeSize(root->right);
} int kthSmallest(TreeNode* root, int k) {
if(root == NULL) return ;
int cnt = calcNodeSize(root->left);
if(k == cnt + ) return root->val;
else if( k < cnt + ) return kthSmallest(root->left,k);
else return kthSmallest(root->right, k-cnt-);
}
};

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,498
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,137
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,301