package BinarySearch;
public class BinarySearchTree {
private Node root = null;
public BinarySearchTree(int[] elements) {
if (elements != null && elements.length >= 1) {
for (int element : elements) {
insert(element);
}
}
}
public boolean delete(int value) {
return operation(value, false, true);
}
private void deleteNode(Node deleteNode) {
boolean isLeftNull = deleteNode.left == null;
boolean isRightNull = deleteNode.right == null;
if (isLeftNull && isRightNull) {
deleteNode = null;
} else if (isLeftNull) {
Node rightNode = deleteNode.right;
deleteNode.value = deleteNode.right.value;
deleteNode.left = rightNode.left;
deleteNode.right = rightNode.right;
} else if (isRightNull) {
Node leftNode = deleteNode.left;
deleteNode.value = deleteNode.left.value;
deleteNode.left = leftNode.left;
deleteNode.right = leftNode.right;
} else {
Node tempLeftNode = deleteNode.left;
Node lastLeftTreeRightNode = tempLeftNode;
Node lastLeftTreeRightNodeParent = null;
while (lastLeftTreeRightNode.right != null) {
lastLeftTreeRightNodeParent = lastLeftTreeRightNode;
lastLeftTreeRightNode = lastLeftTreeRightNode.right;
}
deleteNode.value = lastLeftTreeRightNode.value;
if (lastLeftTreeRightNodeParent != null) {
lastLeftTreeRightNodeParent.right = lastLeftTreeRightNode.left;
}
lastLeftTreeRightNode = null;
}
}
public boolean search(int value) {
return !operation(value, false, false);
}
public boolean insert(int value) {
return operation(value, true, false);
}
private boolean operation(int value, boolean insert, boolean delete) {
if (root == null) {
if (insert) root = new Node(value);
else if (delete) return false;
return true;
}
Node tempRoot = root;
while (true) {
if (value == tempRoot.value) {
if (delete) {
deleteNode(tempRoot);
return true;
}
return false;
} else if (value > tempRoot.value) {
if (tempRoot.right == null) {
if (insert) {
tempRoot.right = new Node(value);
} else if (delete) {
return false;
}
return true;
}
tempRoot = tempRoot.right;
} else {
if (tempRoot.left == null) {
if (insert) {
tempRoot.left = new Node(value);
} else if (delete) {
return false;
}
return true;
}
tempRoot = tempRoot.left;
}
}
}
private static class Node {
private int value;
private Node left;
private Node right;
public Node(int value) {
this.value = value;
}
}
}