Skip to content

Commit 3dcd6c7

Browse files
committed
Create problem30.c
1 parent 7ab87a6 commit 3dcd6c7

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

problem30.c

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
//Solution by Pavithra B, 111712205071, IT dept.
2+
3+
#include <stdio.h>
4+
#include <stdlib.h>
5+
6+
/* A binary tree node has data, pointer to left child
7+
and a pointer to right child */
8+
struct node
9+
{
10+
int data;
11+
struct node* left;
12+
struct node* right;
13+
};
14+
15+
/*Function protoypes*/
16+
void printGivenLevel(struct node* root, int level);
17+
int height(struct node* node);
18+
struct node* newNode(int data);
19+
20+
/* Function to print level order traversal a tree*/
21+
void printLevelOrder(struct node* root)
22+
{
23+
int h = height(root);
24+
int i;
25+
for(i=1; i<=h; i++)
26+
printGivenLevel(root, i);
27+
}
28+
29+
/* Print nodes at a given level */
30+
void printGivenLevel(struct node* root, int level)
31+
{
32+
if(root == NULL)
33+
return;
34+
if(level == 1)
35+
printf("%d ", root->data);
36+
else if (level > 1)
37+
{
38+
printGivenLevel(root->left, level-1);
39+
printGivenLevel(root->right, level-1);
40+
}
41+
}
42+
43+
/* Compute the "height" of a tree -- the number of
44+
nodes along the longest path from the root node
45+
down to the farthest leaf node.*/
46+
int height(struct node* node)
47+
{
48+
if (node==NULL)
49+
return 0;
50+
else
51+
{
52+
/* compute the height of each subtree */
53+
int lheight = height(node->left);
54+
int rheight = height(node->right);
55+
56+
/* use the larger one */
57+
if (lheight > rheight)
58+
return(lheight+1);
59+
else return(rheight+1);
60+
}
61+
}
62+
63+
/* function that allocates a new node with the
64+
given data and NULL left and right pointers. */
65+
struct node* newNode(int data)
66+
{
67+
struct node* node = (struct node*)
68+
malloc(sizeof(struct node));
69+
node->data = data;
70+
node->left = NULL;
71+
node->right = NULL;
72+
73+
return(node);
74+
}
75+
76+
/* main func to test above functions*/
77+
int main()
78+
{
79+
struct node *root = newNode(1);
80+
root->left = newNode(2);
81+
root->right = newNode(3);
82+
root->left->left = newNode(4);
83+
root->left->right = newNode(5);
84+
85+
printf("Level Order traversal of binary tree is \n");
86+
printLevelOrder(root);
87+
88+
getchar();
89+
return 0;
90+
}

0 commit comments

Comments
 (0)