How would you print out the data in a binary tree, level by
level, starting at the top?

Answer Posted / vadim

print tree by levels not recursive in C language


typedef struct treeNode{
int data;
struct treeNode* left;
struct treeNode* right;
} TreeNode;


typedef struct tree{
TreeNode* root;
} Tree;


typedef struct listNode{
TreeNode* dataPtr;
struct listNode* next;
struct listNode* prev;
} ListNode;

typedef struct list
{
ListNode* head;
ListNode* tail;
} List;



//main function : you still will need to write all the mini
functions that i have used here ...


void printByLevels(Tree tr)
{
TreeNode *curr;
List *lst;

lst=(List *)malloc(sizeof(List));
makeEmptyList(lst);
insertDataToStartDList(lst,tr.root);


while(isEmptyList(lst)!=TRUE)
{
curr=lst->tail->dataPtr;

if (curr->left!=NULL)
insertDataToStartDList(lst,curr->left);

if(curr->right!=NULL)
insertDataToStartDList(lst,curr->right);

printf("%d ",curr->data);
RemoveLastNodeInList(lst);

}//while

}

Is This Answer Correct ?    3 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain the difference between malloc() and calloc() in c?

585


a character or group of characters that defines a register,or a part of storage a) memory b) byte c) address d) linear list

638


a direct address that identifies a location by means of its displacement from a base address or segment a) absolute address b) relative address c) relative mode d) absolute mode

667


What is this pointer in c plus plus?

606


Why do we use int main instead of void main in c?

634






how can I convert a string to a number?

606


What is a program flowchart and explain how does it help in writing a program?

690


What is a ternary operator in c?

666


What is #include cctype?

585


What is local and global variable in c?

627


Differentiate between Macro and ordinary definition.

740


Explain what are compound statements?

614


What is the meaning of && in c?

556


What is the use of bit field?

654


ATM machine and railway reservation class/object diagram

4811