-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathLeetCode_103_6.php
More file actions
44 lines (38 loc) · 980 Bytes
/
LeetCode_103_6.php
File metadata and controls
44 lines (38 loc) · 980 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
42
43
44
<?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 zigzagLevelOrder($root) {
if ($root == null) return [];
// BFS
$this->bfs($root, 0);
return $this->levels;
}
function bfs($root, $level)
{
if ($level % 2 != 0) {
if (!isset($this->levels[$level])) $this->levels[$level] = [];
array_unshift($this->levels[$level], $root->val);
} else {
$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);
}
}
}