-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST_Insertion.java
87 lines (71 loc) · 1.54 KB
/
BST_Insertion.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//Insertion In a Binary Search Tree
package Trees;
class BST_Insertion
{
Node root;
BST_Insertion()
{
root=null;
}
void insert(int item)
{
//this root should be declared on LHS to hold the reference to the Top Node of Tree
//so that global root variable should point to the root node of tree
root=insertrecord(root,item);
}
Node insertrecord(Node root,int item)
{
if(root==null)
{
root=new Node(item);
}
else if(item<=root.data)
{
root.left=insertrecord(root.left,item);
}
else
{
root.right=insertrecord(root.right,item);
}
//if we wnon't return the root's reference to the caller then this root pointing
//to the top node, but it is within this function only and the global root variable
//still point to null, that's why it should be returned to the caller
return root;
}
void inorder()
{
inorderrecursion(root);
}
void inorderrecursion(Node root)
{
if(root!=null)
{
inorderrecursion(root.left);
System.out.println(root.data+" ");
inorderrecursion(root.right);
}
}
class Node
{
int data;
Node left;
Node right;
public Node(int d)
{
data=d;
left=null;
right=null;
}
}
public static void main(String...args)
{
BST_Insertion first=new BST_Insertion();
first.insert(10);
first.insert(20);
first.insert(30);
first.insert(5);
first.insert(7);
first.insert(28);
first.inorder();
}
}