File tree 1 file changed +8
-17
lines changed
my-folder/problems/kth_smallest_element_in_a_bst
1 file changed +8
-17
lines changed Original file line number Diff line number Diff line change @@ -19,28 +19,19 @@ class Solution {
19
19
* @return Integer
20
20
*/
21
21
function kthSmallest($root, $k) {
22
- $this->k = $k;
23
- $depth = 0;
24
- $this->res = null;
25
- $this->DFS($root, $depth);
22
+ $ans = [];
23
+ $this->DFS($root, $k, $ans);
26
24
27
- return $this->res ;
25
+ return $ans[$k-1] ;
28
26
}
29
27
30
- function DFS($root, &$depth){
31
- if($this->res) return;
32
-
33
- if($root->left)
34
- $this->DFS($root->left, $depth);
35
-
36
- $depth++;
37
-
38
- if($depth === $this->k){
39
- $this->res = $root->val;
28
+ function DFS($root, $k, &$ans){
29
+ if(!$root || $k===count($ans)){
40
30
return;
41
31
}
42
32
43
- if($root->right)
44
- $this->DFS($root->right, $depth);
33
+ $this->DFS($root->left, $k, $ans);
34
+ $ans[] = $root->val;
35
+ $this->DFS($root->right, $k, $ans);
45
36
}
46
37
}
You can’t perform that action at this time.
0 commit comments