-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
59587cc
commit 3ef3df6
Showing
1 changed file
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
class BinarySearchTree { | ||
|
||
/* Class containing left and right child of current node and key value*/ | ||
class Node { | ||
int key; | ||
Node left, right; | ||
|
||
public Node(int item) { | ||
key = item; | ||
left = right = null; | ||
} | ||
} | ||
|
||
// Root of BST | ||
Node root; | ||
|
||
// Constructor | ||
BinarySearchTree() { | ||
root = null; | ||
} | ||
|
||
// This method mainly calls insertRec() | ||
void insert(int key) { | ||
root = insertRec(root, key); | ||
} | ||
|
||
/* A recursive function to insert a new key in BST */ | ||
Node insertRec(Node root, int key) { | ||
|
||
/* If the tree is empty, return a new node */ | ||
if (root == null) { | ||
root = new Node(key); | ||
return root; | ||
} | ||
|
||
/* Otherwise, recur down the tree */ | ||
if (key < root.key) | ||
root.left = insertRec(root.left, key); | ||
else if (key > root.key) | ||
root.right = insertRec(root.right, key); | ||
|
||
/* return the (unchanged) node pointer */ | ||
return root; | ||
} | ||
|
||
// This method mainly calls InorderRec() | ||
void inorder() { | ||
inorderRec(root); | ||
} | ||
|
||
// A utility function to do inorder traversal of BST | ||
void inorderRec(Node root) { | ||
if (root != null) { | ||
inorderRec(root.left); | ||
System.out.println(root.key); | ||
inorderRec(root.right); | ||
} | ||
} | ||
|
||
// Driver Program to test above functions | ||
public static void main(String[] args) { | ||
BinarySearchTree tree = new BinarySearchTree(); | ||
|
||
/* Let us create following BST | ||
50 | ||
/ \ | ||
30 70 | ||
/ \ / \ | ||
20 40 60 80 */ | ||
tree.insert(50); | ||
tree.insert(30); | ||
tree.insert(20); | ||
tree.insert(40); | ||
tree.insert(70); | ||
tree.insert(60); | ||
tree.insert(80); | ||
|
||
// print inorder traversal of the BST | ||
tree.inorder(); | ||
} | ||
} | ||
// This code is contributed by Ankur Narain Verma |