1+ package com .thealgorithms .tree ;
2+ import java .util .*;
3+ /*
4+ * A simple implementation of a Binary Search Tree (BST) in Java.
5+ * Supports insertion of integer values and tree traversals: inorder, preorder, and postorder.
6+ */
7+ public class BinarySearchTree {
8+
9+ //node class
10+ static class node {
11+ int data ;
12+ node left ;
13+ node right ;
14+
15+ node (int d ) {
16+ this .data = d ;
17+ }
18+ }
19+
20+ //insert value into BST
21+ public static node insert_recurssive (node root , int d ) {
22+ if (root == null ) {
23+ root = new node (d );
24+ return root ;
25+ }
26+ if (root .data > d ) {
27+ //left subtree
28+ root .left = insert_recurssive (root .left , d );
29+ } else {
30+ //right subtree
31+ root .right = insert_recurssive (root .right , d );
32+ }
33+ return root ;
34+ }
35+
36+ //inorder traversal
37+ public static void inorder (node root ) {
38+ if (root == null ) {
39+ return ;
40+ }
41+ inorder (root .left );
42+ System .out .print (root .data + " " );
43+ inorder (root .right );
44+ }
45+
46+ //postorder traversal
47+ public static void postorder (node root ) {
48+
49+ if (root == null ) {
50+ return ;
51+ }
52+ postorder (root .left );
53+ postorder (root .right );
54+ System .out .print (root .data + " " );
55+ }
56+
57+ //preorder traversal
58+ public static void preorder (node root ) {
59+
60+ if (root == null ) {
61+ return ;
62+ }
63+ System .out .print (root .data + " " );
64+ preorder (root .left );
65+ preorder (root .right );
66+ }
67+
68+ //main method
69+ public static void main (String [] args ) {
70+
71+ Scanner sc = new Scanner (System .in );
72+ System .out .println ("Enter the number of integer elements" );
73+ int n = sc .nextInt ();
74+
75+ int values [] = new int [n ];
76+ System .out .println ("Enter " + n + " values:-" );
77+ for (int i = 0 ; i < n ; i ++)
78+ values [i ] = sc .nextInt ();
79+ sc .close ();
80+ node root = null ;
81+ //insert values into BST
82+ for (int i = 0 ; i < values .length ; i ++) {
83+ root = insert_recurssive (root , values [i ]);
84+ }
85+
86+ //traversal of BST
87+ System .out .println ("Inorder Traversal is:-" );
88+ inorder (root );
89+ System .out .println ("\n Postorder Traversal is:-" );
90+ postorder (root );
91+ System .out .println ("\n Preorder Traversal is:-" );
92+ preorder (root );
93+ }
94+ }
0 commit comments