2020年3月23日
LeetCode 230. Kth Smallest Element in a BST
C++, LeetCode, 算法, 编程
0 Comments
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.
Example 1:
Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
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个元素即可,这里采用非递归的方式中序遍历,借助栈保存节点,当左子树和根节点遍历完了之后,出栈然后进入右子树。具体代码如下:
/**
* 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) {
TreeNode* p = root;
stack<TreeNode*> s;
while (!s.empty() || p)
{
while (p)
{
s.push(p);
p = p->left;
}
if (!s.empty())
{
p = s.top();
if(--k == 0)
return p->val;
s.pop();
p = p->right;
}
}
return -1;
}
};