|
| 1 | +package com.thealgorithms.tree; |
| 2 | + |
| 3 | +public class BinarySearchTree { |
| 4 | + class Node { |
| 5 | + int key; |
| 6 | + Node left,right; |
| 7 | + Node(int key){ |
| 8 | + this.key = key; |
| 9 | + left = right = null; |
| 10 | + } |
| 11 | + |
| 12 | + } |
| 13 | + |
| 14 | + Node root; |
| 15 | + |
| 16 | + public void insert(int key){ |
| 17 | + root = insertRec(root,key); |
| 18 | + } |
| 19 | + |
| 20 | + public Node insertRec(Node root, int key){ |
| 21 | + if(root == null){ |
| 22 | + return new Node(key); |
| 23 | + } |
| 24 | + if(key < root.key){ |
| 25 | + root.left = insertRec(root.left,key); |
| 26 | + }else if (key > root.key){ |
| 27 | + root.right = insertRec(root.right,key); |
| 28 | + } |
| 29 | + return root; |
| 30 | + } |
| 31 | + |
| 32 | + public void inorder(){ |
| 33 | + inorderRec(root); |
| 34 | + } |
| 35 | + |
| 36 | + void inorderRec(Node root){ |
| 37 | + if(root != null){ |
| 38 | + inorderRec(root.left); |
| 39 | + System.out.print(root.key + " "); |
| 40 | + inorderRec(root.right); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public void preOrder(){ |
| 45 | + preOrderRec(root); |
| 46 | + } |
| 47 | + |
| 48 | + void preOrderRec(Node root){ |
| 49 | + if(root !=null){ |
| 50 | + System.out.print(root.key + " "); |
| 51 | + preOrderRec(root.left); |
| 52 | + preOrderRec(root.right); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public void postOrder(){ |
| 57 | + postOrderRec(root); |
| 58 | + } |
| 59 | + |
| 60 | + void postOrderRec(Node root){ |
| 61 | + if(root!=null){ |
| 62 | + postOrderRec(root.left); |
| 63 | + postOrderRec(root.right); |
| 64 | + System.out.print(root.key + " "); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + public static void main(String[] args) { |
| 69 | + BinarySearchTree tree = new BinarySearchTree(); |
| 70 | + // tree.insert(50); |
| 71 | + // tree.insert(30); |
| 72 | + // tree.insert(20); |
| 73 | + // tree.insert(40); |
| 74 | + // tree.insert(70); |
| 75 | + // tree.insert(60); |
| 76 | + // tree.insert(80); |
| 77 | + |
| 78 | + System.out.println("Inorder traversal of the given tree"); |
| 79 | + tree.inorder(); |
| 80 | + System.out.println(); |
| 81 | + |
| 82 | + System.out.println("Preorder traversal of the given tree"); |
| 83 | + tree.preOrder(); |
| 84 | + System.out.println(); |
| 85 | + |
| 86 | + System.out.println("Postorder traversal of the given tree"); |
| 87 | + tree.postOrder(); |
| 88 | + System.out.println(); |
| 89 | + } |
| 90 | +} |
| 91 | + |
0 commit comments