{C++} Simple PostOrder, Clean Code, Beats 99.41%
Intuition\u26A1\n\nWe can mark the nodes with values present in to_delete as NULL and and add its left and right child nodes to our answer.\n\nWe need to use po
## Intuition\u26A1\n\nWe can mark the nodes with values present in `to_delete` as `NULL` and and add its left and right child nodes to our **answer**.\n\nWe need to use **postorder traversal** since before we decide whether to delete a node, we have already examined and potentially deleted its **children**.\n\nThis prevents any **dangling references** in the tree after deletion.\n\n\n## Approach \u2705\n<!-- Describe your approach to solving the problem. -->\n\n- Start traversing the tree and upon encountering a `node->val` present in the map `del` we keep marking those nodes as `NULL` in a **bottom-up manner**.\n\n- After completing the traversal, if the **root** node is not `NULL`, add it to the final result.\n\n- Finally **return** the `ans` vector.\n\n\n> ***P.S : We are not directly using the vector `to_delete` because the time complexity of searching in a vector is $$O(n)$$ which will lead the overall time complexity **to increase to $$O(n*d)$$**. So we use a map instead of a vector.***\n\n<br>\n\n```\nclass Solution {\n\nprivate:\n    void unlinker(TreeNode* &root, unordered_map<int,bool> &del, vector<TreeNode*> &ans){\n        if(!root) return;\n\n        unlinker(root->left,del,ans);\n        unlinker(root->right,del,ans);\n\n        if(del[root->val]){\n            if(root->left) ans.push_back(root->left);\n            if(root->right) ans.push_back(root->right);\n            root = NULL;\n        }\n    }\n\npublic:\n    vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {\n        \n        unordered_map<int,bool> del;\n        for(int i : to_delete) del[i] = true;\n\n        vector<TreeNode*> ans;\n        unlinker(root,del,ans);\n        if(root) ans.push_back(root);\n\n        return ans;\n    }\n};\n```\n\n\n### Complexity \u2B50\n- Time complexity:  $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:  $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n>## *~ Please upvote if you found it helpful\u2764\uFE0F*\n\n<br>\n\n![image.png](https://assets.leetcode.com/users/images/b2f01475-ab3f-4539-9937-47c229e01a3e_1721189284.0098507.png)\n\n\n\n---\n\n
['Array', 'Hash Table', 'Tree', 'Depth-First Search', 'Binary Tree', 'C++']