Monday, November 28, 2011

Depth of a given node in BT


public static int depth(BinaryTree root,int node_value){
       Queue<BinaryTree> q = new LinkedList<BinaryTree>();
       int depth=1;
     
       q.add(root);
       q.add(null);
       while(!q.isEmpty()){
      boolean isAdded =false;
      BinaryTree temp = q.poll();
      if(temp==null)
             depth=depth+1;
      else{
      if(temp.data==node_value)
      return depth;
      if(temp.left!=null){
      isAdded=true;
      q.add(temp.left);
      }
      if(temp.right!=null){
      isAdded=true;
      q.add(temp.right);
      }
      if(isAdded)
         q.add(null);
      }
       }
     return 0;
}

No comments:

Post a Comment