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?
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 1
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 3
进阶:
如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<int> _lst;
public int KthSmallest(TreeNode root, int k) {
_lst=new List<int>();
MidTraver(root);
return _lst[k-1];
}
private void MidTraver(TreeNode current)
{
if(current==null)
return;
MidTraver(current.left);
_lst.Add(current.val);
MidTraver(current.right);
}
}
1. “数组”类算法
2. “链表”类算法
3. “栈”类算法
4. “队列”类算法
5. “递归”类算法
6. “位运算”类算法
7. “字符串”类算法
8. “树”类算法
9. “哈希”类算法
10. “排序”类算法
11. “搜索”类算法
12. “动态规划”类算法
13. “回溯”类算法
14. “数值分析”类算法