Skip to content

Commit bc232df

Browse files
committed
Synced from java to cpp
1 parent 2a09c17 commit bc232df

3 files changed

Lines changed: 64 additions & 0 deletions

File tree

‎cpp/SUMMARY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@
101101
* [Convert Sorted Array to Binary Search Tree](binary-tree/bst/convert-sorted-array-to-binary-search-tree.md)
102102
* [Convert Sorted List to Binary Search Tree](binary-tree/bst/convert-sorted-list-to-binary-search-tree.md)
103103
* [LCA of BST](binary-tree/bst/lca-of-bst.md)
104+
* [Kth Smallest Element in a BST](binary-tree/bst/kth-smallest-element-in-a-bst.md)
104105
* [二叉树的递归](binary-tree/recursion/README.md)
105106
* [Minimum Depth of Binary Tree](binary-tree/recursion/minimum-depth-of-binary-tree.md)
106107
* [Maximum Depth of Binary Tree](binary-tree/recursion/maximum-depth-of-binary-tree.md)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
## Kth Smallest Element in a BST
2+
3+
4+
### 描述
5+
6+
Given a binary search tree, write a function `kthSmallest` to find the kth smallest element in it.
7+
8+
**Note**:
9+
10+
You may assume `k` is always valid, `1 ≤ k ≤` BST's total elements.
11+
12+
**Follow up**:
13+
14+
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?
15+
16+
**Hint**:
17+
18+
* Try to utilize the property of a BST.
19+
* What if you could modify the BST node's structure?
20+
* The optimal runtime complexity is O(height of BST).
21+
22+
23+
### 分析
24+
25+
最简单的办法,中序遍历,即可以得到递增序列,从而可以找到第k大的元素。时间复杂度`O(k)`。
26+
27+
如果能够修改节点的数据结构`TreeNode`,可以增加一个字段`leftCnt`,表示左子树的节点个数。设当前节点为`root`,
28+
29+
* 若 `k == root.leftCnt+1`, 则返回root
30+
* 若 `k > node.leftCnt`, 则 `k -= root.leftCnt+1`, `root=root.right`
31+
* 否则,`node = node.left`
32+
33+
算法复杂度为`O(height of BST)`。
34+
35+
36+
### 解法1
37+
38+
{% if book.java %}
39+
{% codesnippet "./code/kth-smallest-element-in-a-bst."+book.suffix, language=book.suffix %}{% endcodesnippet %}
40+
{% endif %}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Kth Smallest Element in a BST
2+
// Time Complexity: O(k), Space Complexity: O(h)
3+
public class Solution {
4+
public int kthSmallest(TreeNode root, int k) {
5+
Stack<TreeNode> s = new Stack<>();
6+
TreeNode p = root;
7+
8+
while (!s.empty() || p != null) {
9+
if (p != null) {
10+
s.push(p);
11+
p = p.left;
12+
} else {
13+
p = s.pop();
14+
--k;
15+
if (k == 0) {
16+
return p.val;
17+
}
18+
p = p.right;
19+
}
20+
}
21+
return -1;
22+
}
23+
}

0 commit comments

Comments
 (0)