<LeetCode OJ> 230. Kth Smallest Element in a BST
2016-01-22 22:07
295 查看
230. Kth Smallest Element in a BST
My SubmissionsQuestion
Total Accepted: 32753 Total
Submissions: 93019 Difficulty: Medium
给定一个二叉搜索树,写一个函数找到二叉树中第k小的值
Given a binary search tree, write a function
kthSmallestto
find the kth smallest element in it.
Note:
你应该假设k是安全有效的
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:
Try to utilize the property of a BST.
What if you could modify the BST node's structure?
The optimal runtime complexity is O(height of BST).
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
Tree Binary
Search
Show Similar Problems
分析:
思路首先:
本题还是比较简单的,感觉没达到中等难度,就是一个中序遍历嘛!
对于二叉搜索树而言,中序遍历的结果就是这颗二叉树中值的有序的上升序列
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //time,o(lg(n)),space,o(k) class Solution { public: void inorderTraversal(TreeNode* root,int k) { if(root){ inorderTraversal(root->left,k); result.push_back(root->val); if(result.size()==k) return; inorderTraversal(root->right,k); } } int kthSmallest(TreeNode* root, int k) { inorderTraversal(root,k); return result[k-1]; } private: vector<int> result; };
迭代法,复杂度均没有变:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //time,o(lg(n)),space,o(k) class Solution { public: int kthSmallest(TreeNode* root, int k) { stack<TreeNode*> stk; //栈中的顺序就是中序遍历顺序 TreeNode* pCurNode=root; int step=1; while (!stk.empty() ||pCurNode) { while(pCurNode)//先把当前节点的所有左子压完, { stk.push(pCurNode); pCurNode=pCurNode->left; } pCurNode=stk.top(); //访问当前节点 stk.pop(); //栈中去掉此节点 if(step++==k) return pCurNode->val; pCurNode=pCurNode->right;//再访问当前节点的右子树 } } };
学习别人的代码:
int kthSmallest(TreeNode* root, int& k) { if (root) { int x = kthSmallest(root->left, k); return !k ? x : !--k ? root->val : kthSmallest(root->right, k); } }
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50564484
原作者博客:http://blog.csdn.net/ebowtang
相关文章推荐
- 5.5 bisect--数组的二分算法
- Xcode快速插入头文件
- uva 10564 - Paths through the Hourglass 沙漏里的路径 最优解+路径输出
- 单状态机的实现
- 试客小兵是真的吗?试客小兵下载,试客小兵什么时候刷新任务?
- Core Data
- linux服务器安全配置实例(一)引言
- x265-1.7版本-common/framedata.cpp注释
- 2016/1/22 codes
- 随笔
- (2)结构体
- 单线程轮训裸机OS程序
- 结构体练习
- 《笨办法学Python》 第20课手记
- sc7731 Android 5.1 Camera 学习之二 framework 到 HAL接口整理
- __bridge
- python核心编程-GUI程序之标签,按钮,进度条
- boost线程同步
- tomcat与nginx、Apache整合
- python操作RabbiMQ