Here is a c implementation of printing level order for a Binary Tree.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct node { | |
int data; | |
node *left, *right; | |
}node; | |
//prototypes of functions | |
int height (node *); | |
void printLevelOrder(node *); | |
void printGivenLevel(node *, int level); | |
node * newNode(int data); | |
int height(node *temp) | |
{ | |
if (temp == NULL) | |
{ | |
return 0; | |
} | |
else | |
{ | |
int lheight = height(temp->left); | |
int rheight = height(temp->right); | |
if(lheight>rheight) | |
return (lheight+1); | |
else | |
return (rheight+1); | |
} | |
} | |
void printLevelOrder(node *temp) | |
{ | |
if (temp == NULL) | |
{ | |
printf("Tree is empty"); | |
return; | |
} | |
int h = height(temp); | |
for(int i=1; i<=h; i++) | |
{ | |
printf("\n"); | |
printGivenLevel(temp , i); | |
} | |
} | |
void printGivenLevel(node *temp , int level) | |
{ | |
if(temp == NULL) | |
return; | |
if (level == 1) | |
printf("%d", temp->data); | |
else | |
{ | |
printGivenLevel(temp->left, level-1); | |
printGivenLevel(temp->right, level-1); | |
} | |
} | |
node * newNode(int data) | |
{ | |
/* struct node* node = (struct node*) | |
malloc(sizeof(struct node)); | |
node->data = data; | |
node->left = NULL; | |
node->right = NULL; | |
return(node);*/ | |
node * temp = (node *) malloc(sizeof(node)); | |
temp->data = data; | |
temp->left = temp->right = NULL; | |
return temp; | |
} | |
int main() | |
{ | |
node *root = newNode(1); | |
root->left = newNode(2); | |
root->right = newNode(3); | |
root->left->left = newNode(4); | |
root->left->right = newNode(5); | |
printf("Level Order traversal of binary tree is \n"); | |
printLevelOrder(root); | |
getchar(); | |
return 0; | |
} |
No comments:
Post a Comment