Total Complexity | 18 |
Total Lines | 76 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
7 | class TreeNode |
||
8 | { |
||
9 | public $val = 0; |
||
10 | public $left; |
||
11 | public $right; |
||
12 | |||
13 | public function __construct(int $val = 0, $left = null, $right = null) |
||
14 | { |
||
15 | $this->val = $val; |
||
16 | $this->left = $left; |
||
17 | $this->right = $right; |
||
18 | } |
||
19 | |||
20 | public static function dfsTreeValues(?TreeNode $tree, array &$list): void |
||
21 | { |
||
22 | if ($tree instanceof TreeNode) { |
||
23 | $list[] = $tree->val ?: null; |
||
24 | |||
25 | if ($tree->left) { |
||
26 | self::dfsTreeValues($tree->left, $list); |
||
27 | } |
||
28 | if ($tree->right) { |
||
29 | self::dfsTreeValues($tree->right, $list); |
||
30 | } |
||
31 | } |
||
32 | } |
||
33 | |||
34 | public static function bfsTreeValues(?TreeNode $tree): array |
||
35 | { |
||
36 | if (!$tree) { |
||
37 | return []; |
||
38 | } |
||
39 | $ans = $queue = []; |
||
|
|||
40 | $queue = [$tree]; |
||
41 | while ($queue) { |
||
42 | /** @var TreeNode $node */ |
||
43 | $node = array_shift($queue); |
||
44 | array_push($ans, $node->val ?: null); |
||
45 | if ($node->left) { |
||
46 | array_push($queue, $node->left); |
||
47 | } |
||
48 | |||
49 | if ($node->right) { |
||
50 | array_push($queue, $node->right); |
||
51 | } |
||
52 | } |
||
53 | |||
54 | return $ans; |
||
55 | } |
||
56 | |||
57 | public static function fromArray(array $array): ?TreeNode |
||
83 | } |
||
84 | } |
||
85 |