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.

Rust Solution

struct Solution;
use rustgym_util::*;
use std::collections::HashSet;
use std::iter::FromIterator;

trait Postorder {
    fn postorder(self, nodes: &HashSet<i32>) -> (TreeLink, Vec<TreeLink>);
}

impl Postorder for TreeLink {
    fn postorder(self, nodes: &HashSet<i32>) -> (TreeLink, Vec<TreeLink>) {
        if let Some(node) = self {
            let val = node.borrow_mut().val;
            let left = node.borrow_mut().left.take();
            let right = node.borrow_mut().right.take();
            let (left_root, left_forest) = left.postorder(nodes);
            let (right_root, right_forest) = right.postorder(nodes);
            let mut forest = vec![];
            for t in left_forest {
                forest.push(t);
            }
            for t in right_forest {
                forest.push(t);
            }
            if nodes.contains(&val) {
                if left_root.is_some() {
                    forest.push(left_root);
                }
                if right_root.is_some() {
                    forest.push(right_root);
                }
                (None, forest)
            } else {
                node.borrow_mut().left = left_root;
                node.borrow_mut().right = right_root;
                (Some(node), forest)
            }
        } else {
            (None, vec![])
        }
    }
}

impl Solution {
    fn del_nodes(root: TreeLink, to_delete: Vec<i32>) -> Vec<TreeLink> {
        let nodes = HashSet::from_iter(to_delete);
        let mut res = vec![];
        let (root, forest) = root.postorder(&nodes);
        if root.is_some() {
            res.push(root);
        }
        for t in forest {
            res.push(t);
        }
        res
    }
}

#[test]
fn test() {
    let root = tree!(
        1,
        tree!(2, tree!(4), tree!(5)),
        tree!(3, tree!(6), tree!(7))
    );
    let to_delete = vec![3, 5];
    let res = vec![tree!(1, tree!(2, tree!(4), None), None), tree!(6), tree!(7)];
    assert_eq!(Solution::del_nodes(root, to_delete), res);
}

Having problems with this solution? Click here to submit an issue on github.