1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace leetcode; |
||
6 | |||
7 | use leetcode\util\TreeNode; |
||
8 | |||
9 | class InvertBinaryTree |
||
10 | { |
||
11 | public static function invertTree(?TreeNode $root): ?TreeNode |
||
12 | { |
||
13 | if (!$root) { |
||
14 | return null; |
||
15 | } |
||
16 | $node = $root->left; |
||
17 | $root->left = $root->right; |
||
18 | $root->right = $node; |
||
19 | |||
20 | self::invertTree($root->left); |
||
21 | self::invertTree($root->right); |
||
22 | |||
23 | return $root; |
||
24 | } |
||
25 | |||
26 | public static function invertTree2(?TreeNode $root): ?TreeNode |
||
27 | { |
||
28 | if (!$root) { |
||
29 | return null; |
||
30 | } |
||
31 | $stack = [$root]; |
||
32 | while ($stack) { |
||
0 ignored issues
–
show
|
|||
33 | $node = array_pop($stack); |
||
34 | $left = $node->left; |
||
35 | $node->left = $node->right; |
||
36 | $node->right = $left; |
||
37 | if ($node->left) { |
||
38 | array_push($stack, $node->left); |
||
39 | } |
||
40 | if ($node->right) { |
||
41 | array_push($stack, $node->right); |
||
42 | } |
||
43 | } |
||
44 | |||
45 | return $root; |
||
46 | } |
||
47 | } |
||
48 |
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.