diff --git a/src/main/java/com/thealgorithms/tree/BinarySearchTree.java b/src/main/java/com/thealgorithms/tree/BinarySearchTree.java new file mode 100644 index 000000000000..68bcea52e599 --- /dev/null +++ b/src/main/java/com/thealgorithms/tree/BinarySearchTree.java @@ -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(); + // } +}