-
Notifications
You must be signed in to change notification settings - Fork 1
/
KthSmallestElementInABst.java
62 lines (55 loc) · 1.49 KB
/
KthSmallestElementInABst.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.hncboy;
/**
* @author hncboy
* @date 2021/10/17 13:25
* @description 230.二叉搜索树中第K小的元素
*
* 给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
*
* 示例 1:
* 输入:root = [3,1,4,null,2], k = 1
* 输出:1
*
* 示例 2:
* 输入:root = [5,3,6,2,4,null,null,1], k = 3
* 输出:3
*
* 提示:
* 树中的节点数为 n 。
* 1 <= k <= n <= 104
* 0 <= Node.val <= 104
*
* 进阶:如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法?
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class KthSmallestElementInABst {
private int count;
private int result;
public int kthSmallest(TreeNode root, int _k) {
count = _k;
dfs(root);
return result;
}
private void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
if (--count == 0) {
result = root.val;
return;
}
dfs(root.right);
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}