The Indian Engineer

Problem 1110 Delete Nodes and Return Forest

Posted on Last edited 3 mins

Binary-Tree Pointers Dfs

Problem Statement

Link - Problem 1110

Question

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

image

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

Solution

/**
 * 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:
    void delNode(TreeNode* &root, vector<bool>& todel, vector<TreeNode*>& result){
        if(root != nullptr){
            delNode(root->left,todel,result);
            delNode(root->right,todel,result);
            if(todel[root->val] == true){
                if(root->left)
                    result.push_back(root->left);
                if(root->right)
                    result.push_back(root->right);
                root = nullptr;
            }
        }
        else
            return;
    }
    vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
        vector<bool>todel(1001,false);
        for(const auto it:to_delete)
            todel[it] = true;
        vector<TreeNode*>res;
        delNode(root,todel,res);
        if(root)
            res.push_back(root);
        return res;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
DFS O(n) O(n)

Explanation

1. Intuition

2. Implementation