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 deb865e

Browse files
committed
889
1 parent a17c5e6 commit deb865e

File tree

1 file changed

+47
-0
lines changed
  • Medium/889. Construct Binary Tree from Preorder and Postorder Traversal

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

Comments
(0)

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