|
| 1 | +package binaryTree; |
| 2 | + |
| 3 | +public class BinarySearchTree { |
| 4 | + |
| 5 | +private TreeNode root; |
| 6 | + |
| 7 | +private class TreeNode { |
| 8 | +private int data; |
| 9 | +private TreeNode left; |
| 10 | +private TreeNode right; |
| 11 | + |
| 12 | +public TreeNode(int data) { |
| 13 | +this.data = data; |
| 14 | +} |
| 15 | +} |
| 16 | + |
| 17 | +public void insert(int value) { |
| 18 | +root = insert(root, value); |
| 19 | +} |
| 20 | + |
| 21 | +public TreeNode insert(TreeNode root, int value) { |
| 22 | +if(root == null) { |
| 23 | +root = new TreeNode(value); |
| 24 | +return root; |
| 25 | +} |
| 26 | + |
| 27 | +if(value < root.data) { |
| 28 | +root.left = insert(root.left, value); |
| 29 | +} else { |
| 30 | +root.right = insert(root.right, value); |
| 31 | +} |
| 32 | +return root; |
| 33 | +} |
| 34 | + |
| 35 | +public void inOrder() { |
| 36 | +inOrder(root); |
| 37 | +} |
| 38 | + |
| 39 | +public void inOrder(TreeNode root) { |
| 40 | +if(root == null) { |
| 41 | +return; |
| 42 | +} |
| 43 | +inOrder(root.left); |
| 44 | +System.out.print(root.data + " "); |
| 45 | +inOrder(root.right); |
| 46 | +} |
| 47 | + |
| 48 | +public TreeNode search(int key) { |
| 49 | +return search(root, key); |
| 50 | +} |
| 51 | + |
| 52 | +public TreeNode search(TreeNode root, int key) { |
| 53 | +if(root == null || root.data == key) { // base case |
| 54 | +return root; |
| 55 | +} |
| 56 | + |
| 57 | +if(key < root.data) { |
| 58 | +return search(root.left, key); |
| 59 | +} else { |
| 60 | +return search(root.right, key); |
| 61 | +} |
| 62 | + |
| 63 | +} |
| 64 | + |
| 65 | +public static void main(String[] args) { |
| 66 | + |
| 67 | +BinarySearchTree tree = new BinarySearchTree(); |
| 68 | +tree.insert(10); |
| 69 | +tree.insert(8); |
| 70 | +tree.insert(4); |
| 71 | +tree.insert(1); |
| 72 | + |
| 73 | +tree.inOrder(); |
| 74 | + |
| 75 | +System.out.println(); |
| 76 | + |
| 77 | +if(null != tree.search(10)) { |
| 78 | +System.out.println("Key found !!!"); |
| 79 | +} else { |
| 80 | +System.out.println("Key not found !!!"); |
| 81 | +} |
| 82 | +} |
| 83 | + |
| 84 | +} |
| 85 | + |
| 86 | + |
0 commit comments