Kth Smallest Element in a BST - leetcode 230号题目个人题解
题目要求
Given a binary search tree, write a function kthSmallest
to find the ***k***th 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小的数字。
回想一下,之前我们做过找出一个数组中第k小的数的算法,用的是分治的思想。不过那是在数组中进行查找,而本题不能采用那种做法。
其实这道题目十分简单。既然已经给出了二叉搜索树,也就是说这棵树已经是有序的了,只要用中序的深度优先遍历的到的就是一个从小到大排好的数组。在这里我们不用遍历完所有的节点,因为只需要找到第k小的数字,那么只要在访问第k个节点的时候,把节点上的数字输出就好了。
对于树的深度优先遍历,可以用递归的方式实现。
详细代码
/**此处为树的实现方式
* 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; //count是用于记录遍历到第几个节点的
return dfs(root,k,count);
}
int dfs(TreeNode* n,int k,int& count){
int ans;
if(n->left!=NULL) ans = dfs(n->left,k,count);
if(count == k) return ans;
else count++;
if(count == k) return n->val;
if(n->right != NULL) ans = dfs(n->right,k,count);
return ans;
}
};
结语
写递归函数的时候一定要注意返回条件。
(完)