/* cs */
using System;
class Node<T> where T : struct, IComparable {
private T key;
private Node<T> left, right;
public Node(T key) {
this.left = this.right = null;
this.key = key;
}
public static void insertNode<S>(ref Node<S> root, S key) where S : struct, IComparable {
if (root == null) {
root = new Node<S>(key);
return;
}
if (key.CompareTo(root.key) < 0)
insertNode<S>(ref root.left, key);
else
insertNode<S>(ref root.right, key);
}
public static bool deleteNode<S>(ref Node<S> root, S key) where S : struct, IComparable {
if (root == null) return false;
if (key.CompareTo(root.key) < 0)
return deleteNode<S>(ref root.left, key);
else if (key.CompareTo(root.key) > 0)
return deleteNode<S>(ref root.right, key);
else {
if (root.left == null) {
root = root.right;
} else if (root.right == null) {
root = root.left;
} else { // root.left != null && root.right != null
Node<S> p;
for (p = root.left; p.right != null; p = p.right)
;
p.right = root.right;
root = root.left;
}
}
return true;
}
public void vomitTree<S>(int c) where S : struct, IComparable {
if (this.left != null)
this.left.vomitTree<S>(c + 3);
for (int i = 0; i < c; i++) System.Console.Write(' ');
System.Console.WriteLine(this.key);
if (this.right != null)
this.right.vomitTree<S>(c + 3);
}
};
class BinaryTree {
private Node<int> root;
public BinaryTree() { this.root = null; }
public void insertNode(int key) { Node<int>.insertNode<int>(ref this.root, key); }
public bool deleteNode(int key) { return Node<int>.deleteNode<int>(ref this.root, key); }
public void vomitTree() { if (this.root != null) this.root.vomitTree<int>(0); }
};
class Sample{
public static void Main() {
BinaryTree tree = new BinaryTree();
for (;;) {
System.Console.Write("> ");
int input = int.Parse(System.Console.ReadLine());
if (input < 0)
break;
tree.insertNode(input);
tree.vomitTree();
}
System.Console.WriteLine("deleting.");
for (;;) {
System.Console.Write("> ");
int input = int.Parse(System.Console.ReadLine());
if (input < 0)
break;
if (tree.deleteNode(input))
System.Console.WriteLine("deleted.");
else
System.Console.WriteLine("not found.");
tree.vomitTree();
}
}
}
/* end */