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 772b741

Browse files
committed
Add solution 106.
1 parent 4a21f95 commit 772b741

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[] $inorder
14+
* @param Integer[] $postorder
15+
* @return TreeNode
16+
*/
17+
function buildTree($inorder, $postorder) {
18+
if($inorder==null || count($inorder)==0 || $postorder==null || count($postorder)==0) return null;
19+
return self::recursive($inorder, 0, count($inorder)-1, $postorder, count($postorder)-1);
20+
}
21+
22+
function recursive($inorder, $inStart, $inEnd, $postorder, $postEnd) {
23+
if($inStart>$inEnd || $postEnd<0) return null;
24+
$root=new TreeNode($postorder[$postEnd]);
25+
/**
26+
manually check the index of postorder[postEnd] in inorder arr
27+
**/
28+
$index=0;
29+
while($inorder[$index]!=$root->val) $index++;
30+
$root->left=self::recursive($inorder, $inStart, $index-1, $postorder, $postEnd-1-($inEnd-$index));
31+
$root->right=self::recursive($inorder, $index+1, $inEnd, $postorder, $postEnd-1);
32+
return $root;
33+
}
34+
}

0 commit comments

Comments
(0)

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