1028. Recover a Tree From Preorder Traversal #1346
-
Topics: We run a preorder depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output If a node has only one child, that child is guaranteed to be the left child. Given the output Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to reconstruct a binary tree from its preorder traversal string where each node's depth is indicated by the number of dashes preceding its value. The challenge is to correctly parse the string and build the tree according to the preorder traversal rules, ensuring that each node with a single child has it as the left child. Approach
Let's implement this solution in PHP: 1028. Recover a Tree From Preorder Traversal <?php
/**
* @param String $traversal
* @return TreeNode
*/
function recoverFromPreorder($traversal) {
$nodes = parseNodes($traversal);
if (empty($nodes)) return null;
$root = new TreeNode($nodes[0][0]);
$stack = array();
array_push($stack, array($root, $nodes[0][1]));
$n = count($nodes);
for ($i = 1; $i < $n; $i++) {
$val = $nodes[$i][0];
$depth = $nodes[$i][1];
// Pop stack until parent's depth is found
while (end($stack)[1] != $depth - 1) {
array_pop($stack);
}
$parentPair = end($stack);
$parentNode = $parentPair[0];
$newNode = new TreeNode($val);
if ($parentNode->left === null) {
$parentNode->left = $newNode;
} else {
$parentNode->right = $newNode;
}
array_push($stack, array($newNode, $depth));
}
return $root;
}
/**
* @param $traversal
* @return array
*/
function parseNodes($traversal) {
$nodes = array();
$i = 0;
$n = strlen($traversal);
while ($i < $n) {
// Count dashes
$dashCount = 0;
while ($i < $n && $traversal[$i] == '-') {
$dashCount++;
$i++;
}
// Read number
$num = 0;
while ($i < $n && is_numeric($traversal[$i])) {
$num = $num * 10 + intval($traversal[$i]);
$i++;
}
array_push($nodes, array($num, $dashCount));
}
return $nodes;
}
// Test cases
$traversal1 = "1-2--3--4-5--6--7";
$traversal2 = "1-2--3---4-5--6---7";
$traversal3 = "1-401--349---90--88";
print_r(recoverFromPreorder($traversal1)); //Output: [1,2,5,3,4,6,7]
print_r(recoverFromPreorder($traversal2)); //Output: [1,2,5,3,null,6,null,4,null,7]
print_r(recoverFromPreorder($traversal3)); //Output: [1,401,null,349,88,90]
?> Explanation:
|
Beta Was this translation helpful? Give feedback.
We need to reconstruct a binary tree from its preorder traversal string where each node's depth is indicated by the number of dashes preceding its value. The challenge is to correctly parse the string and build the tree according to the preorder traversal rules, ensuring that each node with a single child has it as the left child.
Approach