File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
solution/0200-0299/0230.Kth Smallest Element in a BST Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -118,6 +118,57 @@ class Solution {
118
118
}
119
119
```
120
120
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
+
121
172
### ** C++**
122
173
123
174
``` cpp
You can’t perform that action at this time.
0 commit comments