Skip to content

Add Binary Search Implemetation in Java #6334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
92 changes: 92 additions & 0 deletions src/main/java/com/thealgorithms/tree/BinarySearchTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.thealgorithms.tree;

public class BinarySearchTree {
class Node {
int key;
Node left;
Node right;
Node(int key) {
this.key = key;
left = null;
right = null;
}
}

Node root;

public void insert(int key) {
root = insertRec(root, key);
}

public Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key) {
root.left = insertRec(root.left, key);
} else if (key > root.key) {
root.right = insertRec(root.right, key);
}
return root;
}

public void inorder() {
inorderRec(root);
}

public void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.key + " ");
inorderRec(root.right);
}
}

public void preOrder() {
preOrderRec(root);
}

public void preOrderRec(Node root) {
if (root != null) {
System.out.print(root.key + " ");
preOrderRec(root.left);
preOrderRec(root.right);
}
}

public void postOrder() {
postOrderRec(root);
}

public void postOrderRec(Node root) {
if (root != null) {
postOrderRec(root.left);
postOrderRec(root.right);
System.out.print(root.key + " ");
}
}

// public static void main(String[] args) {
// BinarySearchTree tree = new BinarySearchTree();
// tree.insert(50);
// tree.insert(30);
// tree.insert(20);
// tree.insert(40);
// tree.insert(70);
// tree.insert(60);
// tree.insert(80);

// System.out.println("Inorder traversal of the given tree");
// tree.inorder();
// System.out.println();

// System.out.println("Preorder traversal of the given tree");
// tree.preOrder();
// System.out.println();

// System.out.println("Postorder traversal of the given tree");
// tree.postOrder();
// System.out.println();
// }
}
Loading