imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | use leetcode\util\TreeNode; |
||
| 8 | |||
| 9 | class KthSmallestElementInABST |
||
| 10 | { |
||
| 11 | public static function kthSmallest(TreeNode $root, int $k): int |
||
| 12 | { |
||
| 13 | if ($k <= 0) { |
||
| 14 | return 0; |
||
| 15 | } |
||
| 16 | $stack = []; |
||
| 17 | while ($root || $stack) { |
||
|
0 ignored issues
–
show
|
|||
| 18 | while ($root && $root->val) { |
||
| 19 | array_push($stack, $root); |
||
| 20 | $root = $root->left; |
||
| 21 | } |
||
| 22 | $root = array_pop($stack); |
||
| 23 | if (--$k === 0) { |
||
| 24 | break; |
||
| 25 | } |
||
| 26 | $root = $root->right; |
||
| 27 | } |
||
| 28 | |||
| 29 | return $root->val; |
||
| 30 | } |
||
| 31 | |||
| 32 | public static function kthSmallest2(TreeNode $root, int $k): int |
||
| 33 | { |
||
| 34 | if ($k <= 0) { |
||
| 35 | return 0; |
||
| 36 | } |
||
| 37 | $n = 0; |
||
| 38 | self::helper($root, $k, $n); |
||
| 39 | |||
| 40 | return $n; |
||
| 41 | } |
||
| 42 | |||
| 43 | private static function helper(?TreeNode $node, int &$k, int &$n) |
||
| 44 | { |
||
| 45 | if ($node instanceof TreeNode && $node->val) { |
||
| 46 | self::helper($node->left, $k, $n); |
||
| 47 | if (--$k === 0) { |
||
| 48 | $n = $node->val; |
||
| 49 | return; |
||
| 50 | } |
||
| 51 | self::helper($node->right, $k, $n); |
||
| 52 | } |
||
| 53 | } |
||
| 54 | } |
||
| 55 |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.