Wednesday, November 20, 2013

Depth/Height of a Binary Tree ( Recursive and Iterative versions )



Algorithm For Recursion : 

1. If tree is empty then return 0
2. Else
     (a) Get the max depth of left subtree recursively  i.e.,
          call maxDepth( tree->left-subtree)
     (a) Get the max depth of right subtree recursively  i.e.,
          call maxDepth( tree->right-subtree)
     (c) Get the max of max depths of left and right
          subtrees and add 1 to it for the current node.
         max_depth = max(max dept of left subtree, 
                             max depth of right subtree)
                             + 1
     (d) Return max_depth

 int depth_rec (Node *root)
{
    if (root == NULL)
        return 0;

    int left , right ;
    left = depth_rec(root->left);
    right = depth_rec(root->right);

    if(left > right)
        return (left+1);
    else
        return (right+1);
} 

How to find height without recursion?

We can use level order traversal to find height without recursion.
 The idea is to traverse level by level.  Whenever move down to a level, increment height by 1
 (height is initialized as 0). 
Count number of nodes at each level, stop traversing when count of nodes at next level is 0. Following is detailed algorithm to find level order traversal using queue.

Create a queue.
Push root into the queue.height = 0
Loop        
 nodeCount = size of queue                
// If number of nodes at this level is 0,
return height        
 if nodeCount is 0               
 return Height;        
 else              
increase Height         
 // Remove nodes of this level and add nodes of         
 // next level       
while (nodeCount > 0)              
pop node from front               
 push its children to queue               
 decrease nodeCount      
 // At this point, queue has nodes of next level


 int depth_iter (Node *root)
{
    Node *temp = NULL;
    int depth =0 ;
    int node_cnt =0 ;

    //Base case
    //if tree is null return
    if (!root)
        return 0;

    //Create a Queue and push root
    Que *Q = CreateQue();
    enQue(Q,root);

    while(1)
    {
         // nodeCount (queue size) indicates number of nodes
         // at current lelvel.
        node_cnt = sizeQue(Q);
        if (node_cnt == 0)
            return depth;
            
        //as nodes are not zero means one more level is there
        depth++;

        // Dequeue all nodes of current level and Enqueue all
        // nodes of next level
    while (node_cnt > 0) {
        temp = deQue(Q);
        if(temp->left)
            enQue(Q,temp->left);
        if(temp->right)
            enQue(Q,temp->right);
        node_cnt--;
        }
    }
}

No comments:

Post a Comment