Skip to content

Commit 49968e7

Browse files
committed
fix: synchronize the Java solution
No.0230.Kth Smallest Element in a BST
1 parent cd709ab commit 49968e7

File tree

1 file changed

+51
-0
lines changed
  • solution/0200-0299/0230.Kth Smallest Element in a BST

1 file changed

+51
-0
lines changed

solution/0200-0299/0230.Kth Smallest Element in a BST/README.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,57 @@ class Solution {
118118
}
119119
```
120120

121+
```java
122+
/**
123+
* Definition for a binary tree node.
124+
* public class TreeNode {
125+
* int val;
126+
* TreeNode left;
127+
* TreeNode right;
128+
* TreeNode() {}
129+
* TreeNode(int val) { this.val = val; }
130+
* TreeNode(int val, TreeNode left, TreeNode right) {
131+
* this.val = val;
132+
* this.left = left;
133+
* this.right = right;
134+
* }
135+
* }
136+
*/
137+
class Solution {
138+
public int kthSmallest(TreeNode root, int k) {
139+
int ans = -1;
140+
while (root != null) {
141+
if (root.left == null) {
142+
--k;
143+
if (k == 0) {
144+
ans = root.val;
145+
return ans;
146+
}
147+
root = root.right;
148+
} else {
149+
TreeNode pre = root.left;
150+
while (pre.right != null && pre.right != root) {
151+
pre = pre.right;
152+
}
153+
if (pre.right == null) {
154+
pre.right = root;
155+
root = root.left;
156+
} else {
157+
--k;
158+
if (k == 0) {
159+
ans = root.val;
160+
return ans;
161+
}
162+
pre.right = null;
163+
root = root.right;
164+
}
165+
}
166+
}
167+
return ans;
168+
}
169+
}
170+
```
171+
121172
### **C++**
122173

123174
```cpp

0 commit comments

Comments
 (0)