/
107.binary-tree-level-order-traversal-ii.php
74 lines (64 loc) · 1.56 KB
/
107.binary-tree-level-order-traversal-ii.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
namespace LeetCode\BinaryTreeLevelOrderTraversalII;
/*
* @lc app=leetcode id=107 lang=php
*
* [107] Binary Tree Level Order Traversal II
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution
{
/**
* @var array
*/
protected $answer = [];
/**
* @param TreeNode $root
* @return Integer[][]
*/
public function levelOrderBottom($root)
{
if (is_null($root->val)) {
return [];
}
$this->answer[0] = [$root->val];
$this->findAnswer($root);
$this->reverse();
return $this->answer;
}
/**
* @param TreeNode $root
*/
private function findAnswer($root, $level = 1)
{
if (is_null($root->val)) {
return;
}
if (!is_null($root->left)) {
$this->answer[$level] = array_merge($this->answer[$level] ?? [], [$root->left->val]);
}
if (!is_null($root->right)) {
$this->answer[$level] = array_merge($this->answer[$level] ?? [], [$root->right->val]);
}
$this->findAnswer($root->left, $level + 1);
$this->findAnswer($root->right, $level + 1);
}
private function reverse()
{
$this->answer = array_reverse($this->answer);
}
}
// @lc code=end