0% found this document useful (0 votes)
21 views2 pages

Binary Search Tree

BinarySearchTree.java file, complete implementation of Binary Search Tree along with inorder, preorder and postorder traversals of the BST

Uploaded by

Abhishek Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views2 pages

Binary Search Tree

BinarySearchTree.java file, complete implementation of Binary Search Tree along with inorder, preorder and postorder traversals of the BST

Uploaded by

Abhishek Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

package binarySearchTree;

class Node {
int data;
Node left, right;

public Node(int el) {


data = el;
left = right = null;
}
}

class BinarySearchTree {

Node root;

BinarySearchTree() {
root = null;
}

void insert(int data) {


root = insert(root, data);
}

Node insert(Node root, int data) {

if (root == null) {
root = new Node(data);
return root;
}
if (data < root.data)
root.left = insert(root.left, data);
else if (data > root.data)
root.right = insert(root.right, data);
return root;
}

void inOrder(Node root) {


if (root != null) {
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
}

void preOrder(Node node) {


if (node == null)
return;
System.out.print(node.data + " ");
preOrder(node.left);
preOrder(node.right);
}

void postOrder(Node node) {


if (node == null)
return;
postOrder(node.left);
postOrder(node.right);
System.out.print(node.data + " ");
}

void inOrder() {
inOrder(root);
}

void postOrder() {
postOrder(root);
}

void preOrder() {
preOrder(root);
}

public static void main(String[] args) {

BinarySearchTree tree = new BinarySearchTree();

tree.insert(10);
tree.insert(20);
tree.insert(30);
tree.insert(40);
tree.insert(50);

System.out.println("InOrder Traversal: ");


tree.inOrder();

System.out.println("\nPreOrder Traversal: ");


tree.preOrder();

System.out.println("\nPostOrder Traversal: ");


tree.postOrder();

}
}

You might also like