-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstruct-binary-tree-from-inorder-and-postorder-traversal.php
55 lines (46 loc) · 1.48 KB
/
construct-binary-tree-from-inorder-and-postorder-traversal.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution {
/**
* @param Integer[] $inorder
* @param Integer[] $postorder
* @return TreeNode
*/
function buildTree($inorder, $postorder) {
/*
echo "inorder:";
print_r($inorder);
echo "postorder:";
print_r($postorder);
echo "\n";
*/
$N = count($inorder);
$value = end($postorder);
if($N == 0) return null;
if($N == 1) return new TreeNode($value, null, null);
$countLeft = 0;
for($i=0; $i<$N;$i++){
if($inorder[$i]!=$value) $countLeft++;
else break;
}
$left1 = array_slice($inorder, 0, $countLeft);
$right1 = array_slice($inorder, $countLeft + 1, $N);
$left2 = array_slice($postorder, 0, $countLeft);
$right2 = array_slice($postorder, $countLeft, $N - $countLeft - 1);
$left = $this->buildTree($left1, $left2);
$right = $this->buildTree($right1, $right2);
return new TreeNode($value, $left, $right);
}
}