|
| 1 | +<?php |
| 2 | +class TreeNode |
| 3 | +{ |
| 4 | + public $val = null; |
| 5 | + public $left = null; |
| 6 | + public $right = null; |
| 7 | + |
| 8 | + public function __construct($val = 0, $left = null, $right = null) |
| 9 | + { |
| 10 | + $this->val = $val; |
| 11 | + $this->left = $left; |
| 12 | + $this->right = $right; |
| 13 | + } |
| 14 | +} |
| 15 | +class Solution |
| 16 | +{ |
| 17 | + public function constructFromPrePost($preorder, $postorder) |
| 18 | + { |
| 19 | + if (empty($preorder) || empty($postorder)) { |
| 20 | + return null; |
| 21 | + } |
| 22 | + |
| 23 | + $root = new TreeNode(array_shift($preorder)); |
| 24 | + |
| 25 | + if (empty($preorder)) { |
| 26 | + return $root; |
| 27 | + } |
| 28 | + |
| 29 | + $leftSubRoot = $preorder[0]; |
| 30 | + $leftSize = array_search($leftSubRoot, $postorder); |
| 31 | + |
| 32 | + $leftPreorder = array_slice($preorder, 0, $leftSize + 1); |
| 33 | + $rightPreorder = array_slice($preorder, $leftSize + 1); |
| 34 | + |
| 35 | + $leftPostorder = array_slice($postorder, 0, $leftSize + 1); |
| 36 | + $rightPostorder = array_slice($postorder, $leftSize + 1, -1); |
| 37 | + |
| 38 | + $root->left = $this->constructFromPrePost($leftPreorder, $leftPostorder); |
| 39 | + $root->right = $this->constructFromPrePost($rightPreorder, $rightPostorder); |
| 40 | + |
| 41 | + return $root; |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +$solution = new Solution(); |
| 46 | + |
| 47 | +$root = $solution->constructFromPrePost([1, 2, 4, 3, 5], [4, 2, 5, 3, 1]); |
0 commit comments