跳至主要内容

1110. Delete Nodes And Return Forest

· 閱讀時間約 2 分鐘

Hint - Recursion

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr, right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete)
{
// Vector to store the resulting forest of trees
// Convert the list of nodes to delete into a set for faster lookup
// Call the helper function to process the tree
// If the root is not deleted, add it to the forest
// Return the forest
}

// Helper function to process each node
helper()
{
// If the node is null, return null

// Recursively process the left and right subtrees

// If the current node is not in the set of nodes to delete, return it

// If the current node is to be deleted, add its children to the forest if they exist

// Delete the current node
// Return null to indicate the node has been deleted
}
};
  • Recursion
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete)
{
vector<TreeNode*> forest;
unordered_set<int> st(to_delete.begin(), to_delete.end());
root = helper(root, st, forest);
if (root) forest.push_back(root);
return forest;
}

TreeNode* helper(TreeNode* node, unordered_set<int>& st, vector<TreeNode*>& forest)
{
if (!node) return nullptr;

node->left = helper(node->left, st, forest);
node->right = helper(node->right, st, forest);

if (!st.count(node->val)) return node;

if (node->left) forest.push_back(node->left);
if (node->right) forest.push_back(node->right);
delete node;
return nullptr;
}
};
  • T: $O(n)$
  • S: $O(n)$