2024-07-17 Daily Challenge

Today I have done leetcode's July LeetCoding Challenge with cpp.

July LeetCoding Challenge 17

Description

Delete Nodes And Return Forest

Given the root of a binary tree, each node in the tree has a distinct value.

After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

Return the roots of the trees in the remaining forest. You may return the result in any order.

 

Example 1:

Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]

Example 2:

Input: root = [1,2,4,null,3], to_delete = [3]
Output: [[1,2,4]]

 

Constraints:

  • The number of nodes in the given tree is at most 1000.
  • Each node has a distinct value between 1 and 1000.
  • to_delete.length <= 1000
  • to_delete contains distinct values between 1 and 1000.

Solution

class Solution {
  TreeNode *solve(TreeNode* root, const set<int>& to_delete, vector<TreeNode*> &answer, bool newRoot = false) {
    if(!root) return nullptr;
    bool del = to_delete.count(root->val);
    if(newRoot && !del) answer.push_back(root);
    root->right = solve(root->right, to_delete, answer, del);
    root->left = solve(root->left, to_delete, answer, del);
    return del ? nullptr : root;
  }
public:
  vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
    if(!root) return {};
    set<int> del_set(to_delete.begin(), to_delete.end());
    vector<TreeNode*> answer;
    solve(root, del_set, answer, true);
    return answer;
  }
};