Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here is my code

in main t is root t.insert(val , t.root);

Java
public AvlNode insert (int value, AvlNode t) { 

	AvlNode newNode =new AvlNode(value);	
	// Find the node and it's parent.
	AvlNode current = root;
	AvlNode parent = null;
	boolean isLeft = false;
	
	if(root==null)
		root=newNode;
	else {

	while (current != null)
	{
	if (value > current.getValue())
	{
	parent = current;
	current = current.getRight();
	isLeft=false;
	}
	else if (value < current.getValue())
	{
	parent = current;
	current = current.getLeft();
	isLeft=true;
	}
	else
	break;
	}

   if(isLeft)
   parent.setLeft(newNode);
   else parent.setRight(newNode);
	}

	//check the balance 
	
	if(t.getLeft()!=null &&t.getRight()!=null)
	{
	if(getDepth(t.getLeft())-getDepth(t.getRight()) >= 2) {
		 if(value<t.getLeft().getValue())
			 singleRotateWithLeft( t,true ); 
		 else
			 doubleRotateWithLeft( t );
	}
	else if(getDepth(t.getRight())-getDepth(t.getLeft()) >= 2){
		 if(value>t.getRight().getValue())
		   singleRotateWithRight(t,true);
		 else
			 doubleRotateWithRight( t );
		 
	}
	}
		return newNode;


   private int getDepth( AvlNode st )   
{   

     if ( st == null )   
        return 0;   
     else    
     {   
       return 1+ Math.max( getDepth( st.left ), getDepth( st.right ) );
           
     }  
  
}


What I have tried:

i tried to handle the Exception by if(t.getLeft()!=null &&t.getRight()!=null)
Posted
Comments
Richard MacCutchan 12-Nov-18 12:05pm    
Use your debugger to find out where the error occurs and why.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900