889. Construct Binary Tree from Preorder and Postorder Traversal #1350
-
Topics: Given two integer arrays, If there exist multiple answers, you can return any of them. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to construct a binary tree from its preorder and postorder traversals. The key challenge is to correctly identify the left and right subtrees from these traversals and recursively build the tree. Approach
Let's implement this solution in PHP: 889. Construct Binary Tree from Preorder and Postorder Traversal <?php
/**
* 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;
}
}
/**
* @param Integer[] $preorder
* @param Integer[] $postorder
* @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;
}
// Helper function to print tree in level-order
function levelOrderTraversal($root) {
if (!$root) return [];
$queue = [$root];
$result = [];
while (!empty($queue)) {
$node = array_shift($queue);
$result[] = $node->val;
if ($node->left) $queue[] = $node->left;
if ($node->right) $queue[] = $node->right;
}
return $result;
}
// Test case
$preorder = [1,2,4,5,3,6,7];
$postorder = [4,5,2,6,7,3,1];
$tree = constructFromPrePost($preorder, $postorder);
print_r(levelOrderTraversal($tree)); // Expected Output: [1,2,3,4,5,6,7]
?> Explanation:
This approach efficiently reconstructs the binary tree by leveraging the properties of preorder and postorder traversals, ensuring correctness through recursive subdivision of the traversal arrays. |
Beta Was this translation helpful? Give feedback.
We need to construct a binary tree from its preorder and postorder traversals. The key challenge is to correctly identify the left and right subtrees from these traversals and recursively build the tree.
Approach