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 4a21f95

Browse files
committed
Add solution 105.
1 parent d3300b9 commit 4a21f95

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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[] $preorder
14+
* @param Integer[] $inorder
15+
* @return TreeNode
16+
*/
17+
function buildTree($preorder, $inorder) {
18+
$map = [];
19+
for ($i = 0; $i < count($inorder); $i++) {
20+
$map[$inorder[$i]] = $i;
21+
}
22+
return self::helper($preorder, $inorder, $map, 0, 0, count($inorder) - 1);
23+
}
24+
function helper($preorder, $inorder, $map, $index, $start, $end) {
25+
if ($index >= count($preorder) || $start > $end) {
26+
return null;
27+
}
28+
$root = new TreeNode($preorder[$index]);
29+
$k = $map[$root->val];
30+
$root->left = self::helper($preorder, $inorder, $map, $index + 1, $start, $k - 1);
31+
$root->right = self::helper($preorder, $inorder, $map, $index + 1 + $k - $start, $k + 1, $end);
32+
return $root;
33+
}
34+
}

0 commit comments

Comments
(0)

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