Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a865b04

Browse files
committed
Add solution 107.
1 parent 772b741 commit a865b04

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* public $val = null;
5+
* public $left = null;
6+
* public $right = null;
7+
* function __construct($value) { $this->val = $value; }
8+
* }
9+
*/
10+
class Solution {
11+
12+
/**
13+
* @param TreeNode $root
14+
* @return Integer[][]
15+
*/
16+
function levelOrderBottom($root) {
17+
$result = [];
18+
// Hit the end, return an empty list directly
19+
if ($root == null) {
20+
return $result;
21+
}
22+
23+
$self = [];
24+
array_push($self, $root->val);
25+
26+
$left = self::levelOrderBottom($root->left);
27+
$right = self::levelOrderBottom($root->right);
28+
29+
// Return directly on leaf will cause the depth of left/right tree are not the same
30+
// need to merge the lists based on different index.
31+
$startIdx = abs(count($left) - count($right));
32+
if (count($left) >= count($right)) {
33+
for ($i = $startIdx, $j = 0; $j < count($right); $j++) {
34+
array_push($left[$i + $j], ...$right[$j]);
35+
}
36+
array_push($left, $self);
37+
return $left;
38+
} else {
39+
for ($i = $startIdx, $j = 0; $j < count($left); $j++) {
40+
array_splice($right[$i + $j], 0, 0, $left[$j]);
41+
}
42+
array_push($right, $self);
43+
return $right;
44+
}
45+
}
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /