using System;
using System.Collections.Generic;
namespace kdtree {
class Node {
public int[] point;
public Node left;
public Node right;
public Node(int[] point)
{
this.point = point;
this.left = null;
this.right = null;
}
}
class Program {
static int k = 2;
static Node insertRec(Node root, int[] point, int depth)
{
if (root == null) {
return new Node(point);
}
int cd = depth % k;
if (point[cd] < root.point[cd]) {
root.left
= insertRec(root.left, point, depth + 1);
}
else {
root.right
= insertRec(root.right, point, depth + 1);
}
return root;
}
static Node insert(Node root, int[] point)
{
return insertRec(root, point, 0);
}
static Node minNode(Node x, Node y, Node z, int d)
{
Node res = x;
if (y != null && y.point[d] < res.point[d]) {
res = y;
}
if (z != null && z.point[d] < res.point[d]) {
res = z;
}
return res;
}
static Node findMinRec(Node root, int d, int depth)
{
if (root == null) {
return null;
}
int cd = depth % k;
if (cd == d) {
if (root.left == null) {
return root;
}
return findMinRec(root.left, d, depth + 1);
}
return minNode(
root, findMinRec(root.left, d, depth + 1),
findMinRec(root.right, d, depth + 1), d);
}
static Node findMin(Node root, int d)
{
return findMinRec(root, d, 0);
}
static bool arePointsSame(int[] point1, int[] point2)
{
for (int i = 0; i < k; ++i) {
if (point1[i] != point2[i]) {
return false;
}
}
return true;
}
static void copyPoint(int[] p1, int[] p2)
{
for (int i = 0; i < k; i++) {
p1[i] = p2[i];
}
}
static Node deleteNodeRec(Node root, int[] point,
int depth)
{
if (root == null) {
return null;
}
int cd = depth % k;
if (arePointsSame(root.point, point)) {
if (root.right != null) {
Node min = findMin(root.right, cd);
copyPoint(root.point, min.point);
root.right = deleteNodeRec(
root.right, min.point, depth + 1);
}
else if (root.left != null) {
Node min = findMin(root.left, cd);
copyPoint(root.point, min.point);
root.right = deleteNodeRec(
root.left, min.point, depth + 1);
}
else
{
root = null;
return null;
}
return root;
}
if (point[cd] < root.point[cd]) {
root.left = deleteNodeRec(root.left, point,
depth + 1);
}
else {
root.right = deleteNodeRec(root.right, point,
depth + 1);
}
return root;
}
static Node deleteNode(Node root, int[] point)
{
return deleteNodeRec(root, point, 0);
}
static void Main(string[] args)
{
Node root = null;
int[][] points = new int[][] {
new int[] { 30, 40 }, new int[] { 5, 25 },
new int[] { 70, 70 }, new int[] { 10, 12 },
new int[] { 50, 30 }, new int[] { 35, 45 }
};
int n = points.Length;
for (int i = 0; i < n; i++) {
root = insert(root, points[i]);
}
root = deleteNode(root, points[0]);
Console.WriteLine(
"Root after deletion of (30, 40)");
Console.WriteLine(root.point[0] + ","
+ root.point[1]);
}
}
}