Skip to content

Commit

Permalink
#1350, #1351 leetcode problems 000889-construct-binary-tree-from-preo…
Browse files Browse the repository at this point in the history
…rder-and-postorder-traversal submissions 1552937068

Co-authored-by: kovatz <[email protected]>
Co-authored-by: topugit <[email protected]>
Co-authored-by: basharul-siddike <[email protected]>
Co-authored-by: hafijul233 <[email protected]>
  • Loading branch information
5 people committed Feb 23, 2025
1 parent 0018596 commit 3610649
Showing 1 changed file with 6 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,29 +69,12 @@ class TreeNode {
* @return TreeNode
*/
function constructFromPrePost($preorder, $postorder) {
if (empty($preorder)) {
return null;
}
$rootVal = $preorder[0];
$root = new TreeNode($rootVal);
$n = count($preorder);
if ($n == 1) {
return $root;
}
$leftVal = $preorder[1];
$leftPostIdx = array_search($leftVal, $postorder);
$leftSize = $leftPostIdx + 1;

$leftPre = array_slice($preorder, 1, $leftSize);
$leftPost = array_slice($postorder, 0, $leftSize);

$rightPre = array_slice($preorder, $leftSize + 1);
$rightPost = array_slice($postorder, $leftSize, $n - $leftSize - 1);

$root->left = constructFromPrePost($leftPre, $leftPost);
$root->right = constructFromPrePost($rightPre, $rightPost);

return $root;
...
...
...
/**
* go to ./solution.php
*/
}

// Helper function to print tree in level-order
Expand Down

0 comments on commit 3610649

Please sign in to comment.