The height of a binary tree is the number of edges on the longest path from the root node (topmost node) to the farthest leaf node (a node with no children).
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
#include <iostream>
using namespace std;
// Definition of Node
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
// Function to calculate the height of the binary tree
int height_of_binary_tree(Node* root) {
if (root == nullptr)
return 0;
int leftHeight = height_of_binary_tree(root->left);
int rightHeight = height_of_binary_tree(root->right);
return max(leftHeight, rightHeight) + 1;
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->left->right->right = new Node(8);
root->right->left = new Node(6);
root->right->right = new Node(7);
cout << "Height of the binary tree: " << height_of_binary_tree(root);
return 0;
}
Height of the binary tree: 4
height = 0
.node_count
).#include <iostream>
#include <queue>
using namespace std;
// Definition of Node
struct Node {
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
// Function to calculate the height of the binary tree
int height_of_binary_tree(Node* root) {
if (root == nullptr)
return 0;
queue<Node*> q;
q.push(root);
int height = 0;
while (!q.empty()) {
int node_count = q.size(); // Number of nodes at current level
while (node_count > 0) {
Node* current = q.front();
q.pop();
if (current->left)
q.push(current->left);
if (current->right)
q.push(current->right);
node_count--;
}
height++;
}
return height;
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->left->right->right = new Node(8);
root->right->left = new Node(6);
root->right->right = new Node(7);
cout << "Height of the binary tree: " << height_of_binary_tree(root);
return 0;
}
Height of the binary tree: 4
Aspect | Recursive | Iterative |
---|---|---|
Approach | Divide-and-conquer | Level-order traversal |
Space Complexity | O(h) (stack space) | O(w) (queue space) |
Ease of Implementation | Simpler to implement | Requires explicit queue management |
Understanding the height of a binary tree is crucial in tree-based problems. While the recursive approach is simpler to implement, the iterative approach using level order traversal is efficient in managing stack space. Mastering both methods will strengthen your understanding of binary trees in data structures.
CLICK HERE TO KNOW MORE OUR PROGRAM!