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