LeetCode:Kth Smallest Element in a BST
2015-08-14 16:24
204 查看
Given a binary search tree, write a function
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?
思路:BST中序遍历 得到有序序列 以下用的是递归 ,当然也可以用栈
解法一:看leetcode提交记录
代码二:
kthSmallestto 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?
思路:BST中序遍历 得到有序序列 以下用的是递归 ,当然也可以用栈
解法一:看leetcode提交记录
/** * 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 { private: int count=0; int result=0; public: int kthSmallest(TreeNode* root, int k) { if(root==NULL) return 0; kthSmallest(root->left,k); if(count<k) { count++; if(count==k) result=root->val; } if(root->right!=NULL) kthSmallest(root->right,k); return result; } };
代码二:
/** * 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) { int count=0; int result=0; inorderTraversal(root,count,result,k); return result; } void inorderTraversal(TreeNode *node,int &count,int &result,int &k) { if(node==NULL) return; inorderTraversal(node->left,count,result,k); if(count<k) {count++; if(count==k) { result=node->val; return ; } } inorderTraversal(node->right,count,result,k); } };
相关文章推荐
- 判断素数——Dirichlet's Theorem on Arithmetic Progressions
- MFC 如何在项目中定义宏定义
- CodeForces 245C Game with Coins
- Apache Shiro 使用手册(一)Shiro架构介绍 - kdboy - ITeye技术网站
- excel 补全所有空格
- 递归反转一个栈
- OS X Lion版 如果我忘记了我的账户密码 我该怎么办?
- MySQL 5.6 中 TIMESTAMP有那些变化
- 如何实现多线程下载文件
- Android中定时器的3种实现方法
- BZOJ1024
- hdu oj 1849 Rabbit and Grass
- 定时器
- 获取编译学习笔记 (十三)—— 外部中断
- asp.net mvc邮箱激活
- 有哪几种情况只能用intialization list 而不能用assignment
- net view
- Android国际化
- 关于蓝牙
- 《转》QT界面怎么使控件随窗口大小变化一直居中显示