Saturday, 11 January 2014

Print out linked list of elements at each level of Binary Tree

queue<node *> q;
vector<node*> listVec;
int cntr = 0;
int level=0;

void convertLinkedList(node *ptr){
q.push(ptr);
cntr = 1;
while(!q.empty()){
level++;
int sz = cntr;
cntr = 0;
node *head = NULL;
node *prev = NULL;
for(int i = 0;i<sz;i++){
node *nd = q.front();
node *nn1 = new node;
nn1->data = q.front()->data;
nn1->right = NULL;
q.pop();
if(!head){
head = nn1;
prev = nn1;
}else{
prev->right = nn1;
prev = nn1;
}
if(nd->left || nd->right){
if(nd->left){
q.push(nd->left);
cntr++;
}
if(nd->right){
q.push(nd->right);
cntr++;
}
}
}
listVec.push_back(head);
}
}

No comments:

Post a Comment