1110. Delete Nodes And Return Forest

Back to Homepage   |     Back to Code List


class Solution {
    public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
        List<TreeNode> res = new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        for (int d : to_delete) {
            set.add(d);
        }
        
        Deque<TreeNode> stack = new ArrayDeque<>();
        stack.push(root);
        res.add(root);

        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            
            if (set.contains(cur.val)) {
                res.remove(cur);
                if (cur.left != null) res.add(cur.left);
                if (cur.right != null) res.add(cur.right);
            }
            
            if (cur.left != null) {
                stack.push(cur.left);
                if (set.contains(cur.left.val)) {
                    cur.left = null;
                }
            }
            
            if (cur.right != null) {
                stack.push(cur.right);
                if (set.contains(cur.right.val)) {
                    cur.right = null;
                }
            }                       
        }
        
        return res;
    }    
}