LeetCode //C - 1110. Delete Nodes And Return Forest

1110. 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.

From: LeetCode

Link: 1110. Delete Nodes And Return Forest


Solution:

Ideas:

use postorder DFS; when deleting a node, its non-deleted children become new forest roots.

Code:
c 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

struct TreeNode* dfs(struct TreeNode* root, int* del, struct TreeNode** ans, int* returnSize) {
    if (root == NULL) return NULL;

    root->left = dfs(root->left, del, ans, returnSize);
    root->right = dfs(root->right, del, ans, returnSize);

    if (del[root->val]) {
        if (root->left) {
            ans[(*returnSize)++] = root->left;
        }
        if (root->right) {
            ans[(*returnSize)++] = root->right;
        }
        return NULL;
    }

    return root;
}

struct TreeNode** delNodes(struct TreeNode* root, int* to_delete, int to_deleteSize, int* returnSize) {
    int del[1001] = {0};

    for (int i = 0; i < to_deleteSize; i++) {
        del[to_delete[i]] = 1;
    }

    struct TreeNode** ans = malloc(sizeof(struct TreeNode*) * 1000);
    *returnSize = 0;

    root = dfs(root, del, ans, returnSize);

    if (root != NULL) {
        ans[(*returnSize)++] = root;
    }

    return ans;
}