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 f0ce081

Browse files
committed
Add solution 95.
1 parent ebd9cd5 commit f0ce081

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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 Integer $n
14+
* @return TreeNode[]
15+
*/
16+
function generateTrees($n) {
17+
if ($n == 0) {
18+
return [];
19+
}
20+
$results = self::helper(1, $n);
21+
return $results;
22+
}
23+
24+
function helper($begin, $end) {
25+
$results = [];
26+
if ($begin > $end) {
27+
array_push($results, null);
28+
return $results;
29+
}
30+
if ($begin == $end) {
31+
array_push($results, new TreeNode($begin));
32+
return $results;
33+
}
34+
35+
for ($i = $begin; $i <= $end; $i++) {
36+
$lstLeft = self::helper($begin, $i - 1);
37+
$lstRight = self::helper($i + 1, $end);
38+
39+
for ($j = 0; $j < count($lstLeft); $j++) {
40+
$lNode = $lstLeft[$j];
41+
for ($k = 0; $k < count($lstRight); $k++) {
42+
$rNode = $lstRight[$k];
43+
$root = new TreeNode($i);
44+
$root->left = $lNode;
45+
$root->right = $rNode;
46+
array_push($results, $root);
47+
}
48+
}
49+
}
50+
return $results;
51+
}
52+
}

0 commit comments

Comments
(0)

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