Wednesday, March 18, 2020

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]]

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
        vector<TreeNode*> ans;
        TreeNode *parent = NULL;
        set<int> st(to_delete.begin(), to_delete.end());
        helper(root, ans, st, parent);
        if (!st.count(root -> val)) {
            ans.push_back(root);
        }
        return ans;
    }
    
    void helper(TreeNode *root, vector<TreeNode*>& ans, set<int>& st, TreeNode * parent) {
        if (root == NULL) {
            return;
        }
        
        if (st.count(root -> val)) {
            if (root -> left != NULL && !st.count(root -> left -> val)) {
                ans.push_back(root -> left);
            }
            if (root -> right != NULL && !st.count(root -> right -> val)) {
                ans.push_back(root -> right);
            }
            if (parent != NULL && parent -> left == root) {
                parent -> left = NULL;
            }
            if (parent != NULL && parent -> right == root) {
                parent -> right = NULL;
            }
        }
        helper(root -> left, ans, st, root);
        helper(root -> right, ans, st, root);
    }
};

No comments:

Post a Comment