Kth Smallest Element in a BST
来源:互联网 发布:网络客服的注意事项 编辑:程序博客网 时间:2024/06/15 19:33
Question
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?
My Solution
/** * 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) { /*中序遍历,取最小的k个*/ int rst, num; rst = middleIterate(root, k, num); return rst; } int middleIterate(TreeNode* root, int k, int& num){ /* 中序遍历树 0. 边界条件:if root == Null then num = 0, return 0; 1. rst = middleIterate(root->left, k, lnum)遍历左子树 2. if lnum >= k then num = lnum, return rst; 3. else if lnum == k - 1 then num = k, return root->val; 4. else k = k - lnum - 1, rst = middleIterate(root->left, k, rnum)遍历右子树 5. num = lnum + rnum + 1, return rst; */ if(NULL == root){ num = 0; return 0; } int r, lnum, rnum; r = middleIterate(root->left, k, lnum); if(lnum >= k){ num = lnum; return r; }else if(k - 1 == lnum) { num = k; return root->val; }else{ k = k - lnum - 1; r = middleIterate(root->right, k, rnum); num = lnum + rnum + 1; return r; } } };
0 0
- #leetcode#Kth Smallest Element in a BST
- 230.Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- bzoj 3309 DZY Loves Math
- centos安装nginx
- android Bitmap内存优化(三) 测量 ImageView 大小
- java上的缓存框架-Ehcache,redis,memCache
- 国虽大 好战必亡 天下虽安 忘战必危
- Kth Smallest Element in a BST
- 第9章 进程关系
- 第58讲:Scala中Abstract Types实战详解学习笔记
- Java_jdbc 基础笔记之三 数据库连接 (Statement)
- LA 3708 Graveyard
- 乐观锁与CAS操作
- atlassian JIRA 插件开发(七) — 组成
- Hello World
- 怎么求人眼图像中的噪声