Last active
August 29, 2015 14:00
-
-
Save jitsceait/ee1049b9fa513a5c222c to your computer and use it in GitHub Desktop.
Code for level order printing of 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> | |
#include<math.h> | |
struct node{ | |
int value; | |
struct node *left; | |
struct node *right; | |
}; | |
typedef struct node Node; | |
#define MAX(a,b) a>b ?a:b | |
int height(Node *root){ | |
if(root == NULL) | |
return 0; | |
if(!root->left && !root->right) | |
return 1; | |
int lheight = height(root->left); | |
int rheight = height(root->right); | |
return MAX(lheight, rheight)+1; | |
} | |
void printTreeLevel(Node *root){ | |
int h = height(root); | |
int i; | |
for(i =1; i<=h; i++){ | |
printf("Level %d :", i); | |
printTreeLevelRec(root, i); | |
printf("\n"); | |
} | |
} | |
void printTreeLevelRec(Node * node, int desired){ | |
if(node == NULL) | |
return; | |
if (desired ==1) | |
printf("%d", node->value); | |
printTreeLevelRec(node->left, desired-1); | |
printTreeLevelRec(node->right, desired-1); | |
} | |
Node * create_node(int value){ | |
Node * temp = (Node *)malloc(sizeof(Node)); | |
temp->value = value; | |
temp->right= NULL; | |
temp->left = NULL; | |
} | |
Node * addNode(Node *node, int value){ | |
if(node == NULL){ | |
return create_node(value); | |
} | |
else{ | |
if (node->value > value){ | |
node->left = addNode(node->left, value); | |
} | |
else{ | |
node->right = addNode(node->right, value); | |
} | |
} | |
return node; | |
} | |
/* Driver program for the function written above */ | |
int main(){ | |
Node *root = NULL; | |
Node * last = NULL; | |
Node *ptrToHead = NULL; | |
//Creating a binary tree | |
root = addNode(root,30); | |
root = addNode(root,20); | |
root = addNode(root,15); | |
root = addNode(root,25); | |
root = addNode(root,40); | |
root = addNode(root,37); | |
root = addNode(root,45); | |
printTreeLevel(root); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment