-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy path13.php
44 lines (36 loc) · 944 Bytes
/
13.php
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
/**
* 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
*/
function MyPrint($root)
{
if (empty($root)) return [];
$return = [];
$stack = [];
$cur = 0;
$return[0] = [];
$next = 1;
$i = 0;
$stack[0] = [];
$stack[1] = [];
array_push($stack[0], $root);
while(!empty($stack[$cur]) || !empty($stack[$next])) {
$top = array_shift($stack[$cur]);
array_push($return[$i], $top->val);
if ($left = $top->left) {
array_push($stack[$next], $left);
}
if ($right = $top->right) {
array_push($stack[$next], $right);
}
if (empty($stack[$cur])) {
$cur = 1 - $cur;
$next = 1 - $next;
if (!empty($stack[0]) || !empty($stack[1])) {
$i++;
$return[$i] = [];
}
}
}
return $return;
}