Problem:
Binary Search Tree III

Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.

insert $k$: Insert a node containing $k$ as key into $T$.

find $k$: Report whether $T$ has a node containing $k$.

delete $k$: Delete a node containing $k$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases:

If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$).

If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent.

If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print

Sample Output 1

yes
yes
yes
no
no
no
yes
yes
1 2 3 7 8 22
8 2 1 3 7 22
1 2 8 22
8 2 1 22

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution in Rust (judge verdict: Accepted)

// ALDS1_8_C: Binary Search Tree 3

use std::cell::RefCell;
use std::rc::Rc;
use std::str::FromStr;

fn scan<T: FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().parse().ok().unwrap()
}

#[derive(PartialEq)]
enum BST {
    Node { key: i64, left: Rc<RefCell<BST>>, right: Rc<RefCell<BST>> },
    Nil
}

impl BST {
    fn new() -> BST {
        BST::Nil
    }
    fn insert(&mut self, k: i64) {
        match *self {
            BST::Nil => {
                *self = BST::Node {
                    key:k,
                    left: Rc::new(RefCell::new(BST::Nil)),
                    right: Rc::new(RefCell::new(BST::Nil)),
                }
            },
            BST::Node { ref mut key, ref mut left, ref mut right } => {
                if k < *key {
                    left.borrow_mut().insert(k);
                } else {
                    right.borrow_mut().insert(k);
                }
            }
        }
    }
    fn find(&self, k: i64) -> bool {
        match *self {
            BST::Nil => { 
                false
            },
            BST::Node { ref key, ref left, ref right} => {
                if k < *key {
                    left.borrow().find(k)
                } else if k > *key {
                    right.borrow().find(k)
                } else {
                    true
                }
            }
        }
    }
     fn delete(&mut self, k: i64) {
        let mut delete_self = false;
        let mut x = None;
        match *self {
            BST::Nil => {},
            BST::Node { ref mut key, ref left, ref right} => {
                if k == *key {
                    if *left.borrow() == BST::Nil && *right.borrow() == BST::Nil {
                        delete_self = true;
                    } else if *right.borrow() == BST::Nil {
                        x = Some(Rc::clone(left));
                    } else if *left.borrow() == BST::Nil {
                        x = Some(Rc::clone(right));
                    } else {
                        if let Some(m) = Self::tree_minimum(right.clone()) {
                           right.borrow_mut().delete(m);
                           *key = m;
                        }
                    }
                } else if k < *key {
                    left.borrow_mut().delete(k);
                } else {
                    right.borrow_mut().delete(k);
                }
            }
        }
        if delete_self {
            *self = BST::Nil;
        } else if let Some(x) = x {
            match *x.borrow() {
                BST::Nil => {},
                BST::Node { ref key, ref left, ref right } => {
                    *self = BST::Node {
                        key: *key,
                        left: left.clone(),
                        right: right.clone(),
                    };
                }
            }
        }
    }
    fn tree_minimum(node: Rc<RefCell<BST>>) -> Option<i64> {
        match *node.borrow() {
            BST::Nil => {
                None
            },
            BST::Node { key, ref left, right: _ } => {
                match *left.borrow() {
                    BST::Nil => { 
                        Some(key)
                    },
                    BST::Node {..} => {
                        Self::tree_minimum(left.clone())
                    }
                }
            }
        }
    }
    fn preorder(&self) {
        match *self {
            BST::Nil => {},
            BST::Node { ref key, ref left, ref right} => {
                print!(" {}", *key);
                left.borrow().preorder();
                right.borrow().preorder();
            }
        }
    }
    fn inorder(&self) {
        match *self {
            BST::Nil => {},
            BST::Node { ref key, ref left, ref right } => {
                left.borrow().inorder();
                print!(" {}", *key);
                right.borrow().inorder();
            }
        }
    }
}

fn main() {
    let n = scan::<usize>();
    let mut t = BST::new();
    for _ in 0..n {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let mut it = s.split_whitespace();
        let com = it.next().unwrap();
        if com == "find" {
            let x = it.next().unwrap().parse::<i64>().ok().unwrap();
            if t.find(x) {
                println!("yes");
            } else {
                println!("no");
            }
        } else if com == "insert" {
            let x = it.next().unwrap().parse::<i64>().ok().unwrap();
            t.insert(x);
        } else if com == "delete" {
            let x = it.next().unwrap().parse::<i64>().ok().unwrap();
            t.delete(x);
        } else if com == "print" {
            t.inorder();
            println!();
            t.preorder();
            println!();
        }
    }
}