-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeBinaryheight.c
63 lines (52 loc) · 1.48 KB
/
TreeBinaryheight.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//QUESTION: Find the height of a binary tree.
//CODE:
#include <stdio.h>
#include <stdlib.h>
// Definition of a tree node
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to insert a node in the binary tree
struct Node* insertNode(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else {
root->right = insertNode(root->right, data);
}
return root;
}
// Function to find the height of a binary tree
int findHeight(struct Node* root) {
if (root == NULL) {
return 0;
}
int leftHeight = findHeight(root->left);
int rightHeight = findHeight(root->right);
// The height of the tree is the maximum height of the left or right subtree, plus 1 for the root node
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
int main() {
struct Node* root = NULL;
root = insertNode(root, 50);
insertNode(root, 30);
insertNode(root, 20);
insertNode(root, 40);
insertNode(root, 70);
insertNode(root, 60);
insertNode(root, 80);
printf("The height of the binary tree is: %d\n", findHeight(root));
return 0;
}