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