Binary Search Tree - Important Algorithms

Binary search tree - Wikipedia

Insertion in Binary Search Tree :


public treeNode insertNode(Node currentNode, int data) {
if(currentNode==null){
currentNode= new treeNode(data);
}
// data moves to right subtree
if(data>currentNode.data){
currentNode.right = insertNode(currentNode.right,data); 
}
//data moves to left subtree
else if(data<=currentNode.data){
currentNode.left = insertNode(currentNode.left,data);
}
return currentNode;


}


Deletion of a node in Binary Search Tree:

public  treeNode deleteNode(treeNode node, int data){
if(root==null) // tree is empty
return null;

if(data<node.data){
node.left = deleteNode(node.left,data);
}
else if(data>root.data){
node.right = deleteNode(node.right,data);
}
// if the current node has the data to delete, consider three cases - 0/1/2 child of current node

// if two child
// find the minimum of the right subtree and replace the current node
with the value found. Also delete the node with min value of the right subtree
// if one child
//If the only child is left child
if(node.left!=null){
node = node.left();
}
// if the only child is right child
else node = node.right();
// if no child
node = null;

return  node;
}

Searching in Binary Search Tree:


public treeNode search(treeNode node, int data) {
if(node==null){
return  null;
}
if(data==node.data){
Print “found”
return node;
}
if(data<node.data){
 search(node.left, data);
}
else{
search(node.right,data);
}
}


Comments

Popular posts from this blog

Quick Sort

Disjoint Set - Implemented Using Arrays

Graph Traversal Code - BFS on Graph represented using Adjacency Matrix