Kth Smallest Element in a BST
第17天,又是一道之前没做出来的题目,然而好像并不难啊。
今天的题目是 Kth Smallest Element in a BST :
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:
1 | Input: root = [3,1,4,null,2], k = 1 |
Example 2:
1 | Input: root = [5,3,6,2,4,null,null,1], k = 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?
题意很简单就是求BST中第k小的数字,然后BST本身就包含一定的顺序信息,利用BST中序遍历是有序的性质,我们可以很快的把这道题写出来:
1 | int res; |
然后我们可以写出非递归版本的:
1 | int kthSmallest(TreeNode* root, int k) { |
BTW,这道题的测试有点不稳定,同一个代码会测试出不同的时间。