1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace leetcode; |
||
6 | |||
7 | use leetcode\util\TreeNode; |
||
8 | |||
9 | class CousinsInBinaryTree |
||
10 | { |
||
11 | private int $xDepth = 0; |
||
12 | private int $yDepth = 0; |
||
13 | private ?TreeNode $xParent = null; |
||
14 | private ?TreeNode $yParent = null; |
||
15 | |||
16 | public static function isCousins(?TreeNode $root, int $x, int $y): bool |
||
17 | { |
||
18 | if (!$root) { |
||
19 | return false; |
||
20 | } |
||
21 | $queue = [$root]; |
||
22 | while ($queue) { |
||
0 ignored issues
–
show
|
|||
23 | [$curr, $n] = [[], count($queue)]; |
||
24 | for ($i = 0; $i < $n; $i++) { |
||
25 | /** @var \leetcode\util\TreeNode $node */ |
||
26 | $node = array_shift($queue); |
||
27 | if ($node->left) { |
||
28 | array_push($queue, $node->left); |
||
29 | $curr[$node->left->val] = $node->val; |
||
30 | } |
||
31 | if ($node->right) { |
||
32 | array_push($queue, $node->right); |
||
33 | $curr[$node->right->val] = $node->val; |
||
34 | } |
||
35 | } |
||
36 | $keys = array_keys($curr); |
||
37 | if (in_array($x, $keys) && in_array($y, $keys) && $curr[$x] !== $curr[$y]) { |
||
38 | return true; |
||
39 | } |
||
40 | } |
||
41 | |||
42 | return false; |
||
43 | } |
||
44 | |||
45 | public function isCousins2(?TreeNode $root, int $x, int $y): bool |
||
46 | { |
||
47 | $this->helper($root, $x, $y, 0, null); |
||
48 | |||
49 | return $this->xDepth === $this->yDepth && $this->xParent !== $this->yParent; |
||
50 | } |
||
51 | |||
52 | public function helper(?TreeNode $node, int $x, int $y, int $depth, ?TreeNode $parent) |
||
53 | { |
||
54 | if (!$node) { |
||
55 | return; |
||
56 | } |
||
57 | if ($node->val === $x) { |
||
58 | [$this->xDepth, $this->xParent] = [$depth, $parent]; |
||
59 | } elseif ($node->val === $y) { |
||
60 | [$this->yDepth, $this->yParent] = [$depth, $parent]; |
||
61 | } else { |
||
62 | $this->helper($node->left, $x, $y, $depth + 1, $node); |
||
63 | $this->helper($node->right, $x, $y, $depth + 1, $node); |
||
64 | } |
||
65 | } |
||
66 | } |
||
67 |
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.