1110. Delete Nodes And Return Forest #59
-
Given the After deleting all nodes with a value in Return the roots of the trees in the remaining forest. You may return the result in any order. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 1110. Delete Nodes And Return Forest <?PHP
class TreeNode {
public $val = null;
public $left = null;
public $right = null;
public function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
class Solution {
/**
* @param TreeNode $root
* @param Integer[] $to_delete
* @return TreeNode[]
*/
function delNodes($root, $to_delete) {
$to_delete_set = array_flip($to_delete);
$forest = [];
$root = $this->helper($root, $forest, $to_delete_set);
if ($root !== null) {
$forest[] = $root;
}
return $forest;
}
/**
* @param $node
* @param $forest
* @param $to_delete_set
* @return mixed|null
*/
function helper($node, &$forest, $to_delete_set) {
if ($node === null) {
return null;
}
$node->left = self::helper($node->left, $forest, $to_delete_set);
$node->right = self::helper($node->right, $forest, $to_delete_set);
if (isset($to_delete_set[$node->val])) {
if ($node->left !== null) {
$forest[] = $node->left;
}
if ($node->right !== null) {
$forest[] = $node->right;
}
return null;
}
return $node;
}
}
// Helper function to build a binary tree from a list
function buildTree($nodes) {
if (empty($nodes)) {
return null;
}
$root = new TreeNode($nodes[0]);
$queue = [$root];
$i = 1;
while ($i < count($nodes)) {
$current = array_shift($queue);
if ($nodes[$i] !== null) {
$current->left = new TreeNode($nodes[$i]);
$queue[] = $current->left;
}
$i++;
if ($i < count($nodes) && $nodes[$i] !== null) {
$current->right = new TreeNode($nodes[$i]);
$queue[] = $current->right;
}
$i++;
}
return $root;
}
// Example usage:
$root = buildTree([1, 2, 3, 4, 5, 6, 7]);
$to_delete = [3, 5];
$forestRoot = new Solution();
$forest = $forestRoot->delNodes($root, $to_delete);
function printForest($forest) {
foreach ($forest as $tree) {
printTree($tree);
echo "\n";
}
}
function printTree($node) {
if ($node === null) {
return;
}
echo $node->val . " ";
printTree($node->left);
printTree($node->right);
}
printForest($forest);
?> Explanation:
Contact Links If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me! If you want more helpful content like this, feel free to follow me: |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 1110. Delete Nodes And Return Forest