Monday, March 7, 2011

Write A Program to Remove Duplicates from BST remember its BST not Binary Tree..

class Node{
int data;
Node left;
Node right;

Node(int data){
this.data=data;
left=null;
right=null;
}
}
class BST{
Node head;

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

public static void main(String args[]){
new BST().go();
}

void go(){
int[] a=new int[]{80,150,70,80,70,70,140,110,110};//test case
for(int i:a)
head=insert(head,i);
inorder(head);
remove(head,-1);//I need an element which cant be in the bst for a neat recursion so i use -1
System.out.println();
inorder(head);
}

void inorder(Node n){
if(n==null)
return;
inorder(n.left);
System.out.print(n.data+" ");
inorder(n.right);
}

boolean remove(Node n,int d){
if(n==null)
return false;
if(remove(n.left,n.data))
n.left=n.left.left;
if(n.data==d)
return true;
if(remove(n.right,d))
n.right=n.right.left;
return false;
}
}

No comments :