1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace leetcode; |
||
6 | |||
7 | use leetcode\util\TreeNode; |
||
8 | |||
9 | class BinaryTreeLevelOrderTraversal |
||
10 | { |
||
11 | public static function levelOrder(TreeNode $root): array |
||
12 | { |
||
13 | $ans = $queue = []; |
||
0 ignored issues
–
show
Unused Code
introduced
by
![]() |
|||
14 | if (empty($root)) { |
||
15 | return $ans; |
||
16 | } |
||
17 | $queue = [$root]; |
||
18 | while ($queue) { |
||
0 ignored issues
–
show
The expression
$queue of type array<integer,leetcode\util\TreeNode> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.
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 ![]() |
|||
19 | $curr = []; |
||
20 | for ($i = 0, $n = count($queue); $i < $n; $i++) { |
||
21 | /** @var \leetcode\util\TreeNode $node */ |
||
22 | $node = array_shift($queue); |
||
23 | $curr[] = $node->val; |
||
24 | if ($node->left !== null) { |
||
25 | $queue[] = $node->left; |
||
26 | } |
||
27 | if ($node->right !== null) { |
||
28 | $queue[] = $node->right; |
||
29 | } |
||
30 | } |
||
31 | $ans[] = $curr; |
||
32 | } |
||
33 | |||
34 | return $ans; |
||
35 | } |
||
36 | |||
37 | public static function levelOrder2(TreeNode $root): array |
||
38 | { |
||
39 | $ans = []; |
||
40 | if (empty($root) || $root === null) { |
||
41 | return $ans; |
||
42 | } |
||
43 | self::helper($ans, $root, 0); |
||
44 | |||
45 | return $ans; |
||
46 | } |
||
47 | |||
48 | private static function helper(array &$ans, TreeNode $node, int $curr): void |
||
49 | { |
||
50 | if ($node === null) { |
||
51 | return; |
||
52 | } |
||
53 | if (count($ans) < $curr + 1) { |
||
54 | $ans[] = []; |
||
55 | } |
||
56 | $ans[$curr][] = $node->val; |
||
57 | |||
58 | if ($node->left) { |
||
59 | self::helper($ans, $node->left, $curr + 1); |
||
60 | } |
||
61 | if ($node->right) { |
||
62 | self::helper($ans, $node->right, $curr + 1); |
||
63 | } |
||
64 | } |
||
65 | } |
||
66 |