Tuesday, February 21, 2012

Data Structure and Algorithm - Binary Tree Alogrithm PrintTree()

Function printTree() in by level of each tree
.....
class bSearchTreeType{
.......
printTree(); 
.......
};


void bSearchTreeType::printTree(){ 
        int level = 0; // initialize of level of tree
/*  Condition for root is NULL ? */
        if(root == NULL)
            return; /*  Exit function if root is NULL */
/*  Create 2 Queues for store pointer of nodeType */
        queueType<nodeType*> currentlevel,nextlevel;
/*  add pointer root into currentLevel */
        currentlevel.addQueue(root);
/*  Condition currentlevel queue is not yet Empty then
    add pointer llink and rlink of each pointer in front queue
    to other nextlevel queue and delete currentlevel queue front
 */
         int x = level; /* is technique to print Level number */
         while(!currentlevel.isEmptyQueue()){
/*  create pointer currNode of nodeType points to
    pointer of currentlevel queue front
    then delete queuefront of currentlevel queue
 */
             nodeType *currNode = currentlevel.front();
             currentlevel.deleteQueue();
             if(currNode){
                 if(x++ == level) // technique to show only once for level
                     cout<<"L["<<level<<"]\t";
                 cout<<currNode->info<<"\t";
                 nextlevel.addQueue(currNode->llink);
                 nextlevel.addQueue(currNode->rlink);
             }
/* end if */
             if(currentlevel.isEmptyQueue()){
                 cout << endl;
                 level++;
                 x = level;
/*  Swap object queue currentlevel and nextlevel */
                 queueType<nodeType*> temp;
                 temp = currentlevel;
                 currentlevel = nextlevel;
                 nextlevel = temp;
             }
/* end if */
         }
/* end while */
    }
/* end if */
}

No comments:

Post a Comment