C Program: Calculate height of Binary Tree with graceful handling
4. Binary Tree Height Calculation Challenges
Write a C program to calculate the height of a binary tree. Ensure the program handles empty trees gracefully.
Sample Solution:
C Code:
Output:
Input a value to insert into the binary tree (enter 0 to stop): 45 Input a value to insert into the binary tree (enter 0 to stop): 18 Input a value to insert into the binary tree (enter 0 to stop): 12 Input a value to insert into the binary tree (enter 0 to stop): 8 Input a value to insert into the binary tree (enter 0 to stop): 4 Input a value to insert into the binary tree (enter 0 to stop): 0 Height of the Binary Tree: 5
Explanation:
In the exercise above,
- Structure Definition (struct TreeNode):
- Defines a structure for a binary tree node (TreeNode) with integer data, and pointers to the left and right children.
- Node Creation Function (createNode):
- Allocates memory for a new node and initializes its data and pointers.
- Node Insertion Function (insertNode):
- Inserts a new node into the binary tree while maintaining the binary search tree property.
- Tree Height Calculation Function (treeHeight):
- Recursively calculates and returns the height of the binary tree.
- Memory Deallocation Function (freeTree):
- Frees the memory allocated for the binary tree nodes.
- Main Function (main):
- Initializes the root of the binary tree to NULL.
- Allows the user to input values to insert into the binary tree until the user enters 0.
- Calls the treeHeight function to calculate and display the height of the binary tree.
- Frees the memory allocated for the binary tree.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to calculate the height of a binary tree iteratively using level order traversal.
- Write a C program to compute both the height and the total number of leaf nodes in a binary tree.
- Write a C program to determine the height of a skewed binary tree where each node only has one child.
- Write a C program to compute the diameter of a binary tree, which is the longest path between any two nodes.
C Programming Code Editor:
Previous: C Program: Binary search Tree insertion with sorted in-order traversal.
Next: C Program: Binary Tree deletion with BST maintenance.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.