Thursday, November 17, 2011

Height of a tree Iterative n recursive pgm


public static void height(BinaryTree root){
int height=-1;
Queue<BinaryTree> q=new LinkedList<BinaryTree>();
BinaryTree curr;
q.add(root);
q.add(null);
while(!q.isEmpty()){
curr=q.poll();
if(curr==null){
height++;
if(!q.isEmpty())
    q.add(null);
}
else{
if(curr.left!=null)
q.add(curr.left);
if(curr.right!=null)
q.add(curr.right);
}
}
System.out.println(height);
}



public static int height_rec(BinaryTree root){
            if(root==null)
return -1;
   else
return(max(height_rec(root.left),height_rec(root.right)) + 1);
}

No comments:

Post a Comment