public class BinarySearchTree {
public class Node{
Node left;
Node right;
int value;
public Node(int value){
this.value = value;
left = null;
right = null;
}
}
private Node root;
public BinarySearchTree(){
root = null;
}
public BinarySearchTree(int[] arr){
for(int i : arr){
insert(i);
}
}
public void insert(int value){
root = insert(root, value);
}
public Node insert(Node root, int value){
if (root == null) {
root = new Node(value);
}else if (value <= root.value) {
if (root.left == null) {
root.left = new Node(value);
}else {
insert(root.left, value);
}
}else {
if (root.right == null) {
root.right = new Node(value);
}else {
insert(root.right, value);
}
}
return root;
}
public void inOrder(Node tree){
if (tree != null) {
inOrder(tree.left);
System.out.print(tree.value + "\t");
inOrder(tree.right);
}
}
public void preOrder(Node tree){
if (tree != null) {
System.out.print(tree.value +"\t");
preOrder(tree.left);
preOrder(tree.right);
}
}
public void postOrder(Node tree){
if (tree != null) {
postOrder(tree.left);
postOrder(tree.right);
System.out.print(tree.value +"\t");
}
}
public Node search(Node tree, int value){
if (tree == null || value == tree.value) {
return tree;
}
if (value <= tree.value) {
return search(tree.left, value);
}else {
return search(tree.right, value);
}
}
public Node searchNoIter(Node root, int value){
while (root != null && value != root.value) {
if (value <= root.value) {
root = root.left;
}else {
root = root.right;
}
}
if (root == null) {
throw new NullPointerException("Null Poninter" + value);
}else {
return root;
}
}
public Node minNode(Node root){
while (root.left != null) {
root = root.left;
}
return root;
}
public Node maxNode(Node root){
while (root.right != null) {
root = root.right;
}
return root;
}
public Node insertNode(Node root, Node x){
if (root == null) {
return new Node(x.value);
}
if (x.value <= root.value) {
root.left = insertNode(root.left, x);
}else {
root.right = insertNode(root.right, x);
}
return root;
}
public Node remove(Node root, int value){
if (root == null) {
return root;
}
if (value < root.value) {
root.left = remove(root.left, value);
}else if (value > root.value) {
root.right = remove(root.right, value);
}else if (root.left != null && root.right != null) {
root.value = minNode(root.right).value;
root.right = remove(root.right, root.value);
}else {
root = (root.left != null)? root.left:root.right;
}
return root;
}