Skip to content

Commit 746aa51

Browse files
committed
Sync LeetCode submission - Kth Smallest Element in a BST (php)
1 parent 76b20bb commit 746aa51

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

my-folder/problems/kth_smallest_element_in_a_bst/solution.php

+8-17
Original file line numberDiff line numberDiff line change
@@ -19,28 +19,19 @@ class Solution {
1919
* @return Integer
2020
*/
2121
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);
2624

27-
return $this->res;
25+
return $ans[$k-1];
2826
}
2927

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)){
4030
return;
4131
}
4232

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);
4536
}
4637
}

0 commit comments

Comments
 (0)