Our Feeds

Thursday, 28 January 2016

AJITH KP

C++ Functions to Build Complete Binary Tree and Print Level By level

Hello Guyz,
This is an important question we can expect in Data Structures paper especially in the section of Binary Tree.
The bellow program code includes the functions to build complete binary tree and print it in level by level. Hope you can understand the algorithm and why Queue is used here.

SOURCE CODE

Enter your text to encode...#include <iostream>
#include <queue>
using namespace std;
/*
 *  Coded By Ajith Kp [@ajithkp560] http://www.terminalcoder.blogspot.com
 */
struct node{
    int data;
    node *lc = NULL;
    node *rc = NULL;
};
class FT{
    node *root;
    int n, v, i;
public:
    void read(){
        cout<<"Enter number of nodes in binary tree: ";
        cin>>n;
    }
    void build(){
        queue<node *> q;
        node *nn, *cn;
        cout<<"Enter nodes: ";
        cin>>v;
        root = new node;
        root->data = v;
        q.push(root);
        i=1;
        while(i<n){
            cn = q.front();
            q.pop();
            cin>>v;
            nn = new node;
            nn->data = v;
            cn->lc = nn;
            q.push(nn);
            i++;
            if(i<n){
                cin>>v;
                nn = new node;
                nn->data = v;
                cn->rc = nn;
                q.push(nn);
                i++;
            }
        }
    }
    void printLevel(){
        queue<node *> q;
        node *cn, *tmp;
        if(root){
            cout<<"Binary Tree Level By Level: ";
            cout<<root->data<<" ";
            q.push(root);
            while(!q.empty()){
                cn = q.front();
                q.pop();
                if(cn->lc){
                    tmp = cn->lc;
                    cout<<tmp->data<<" ";
                    q.push(cn->lc);
                }
                if(cn->rc){
                    tmp = cn->rc;
                    cout<<tmp->data<<" ";
                    q.push(cn->rc);
                }
            }
        }
    }
};
int main(){
    FT ft;
    ft.read();
    ft.build();
    ft.printLevel();
    return 0;
}