-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path102.php
More file actions
41 lines (34 loc) · 780 Bytes
/
Copy path102.php
File metadata and controls
41 lines (34 loc) · 780 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {
public $levels = [];
/**
* @param TreeNode $root
* @return Integer[][]
*/
function levelOrder($root)
{
if ($root == null) return [];
// BFS
$this->bfs($root, 0);
return $this->levels;
}
function bfs($root, $level)
{
$this->levels[$level][] = $root->val;
if ($root->left != null) {
$this->bfs($root->left, $level + 1);
}
if ($root->right != null) {
$this->bfs($root->right, $level + 1);
}
}
}