height of a binary tree
The height of a binary tree is the maximum number of edges between the root node and any leaf node in the tree. It represents the depth or levels of the tree.
To calculate the height of a binary tree, we can use a recursive approach. Here is an explanation of the steps involved:
- Base case:
If the tree is empty (i.e., the root is null), the height is considered as 0.
Recursive step:
- If the tree is not empty, we recursively calculate the height of the left and right subtrees.
We find the maximum height between the left and right subtrees and add 1 to it (to account for the root node).
Return the height:
- The height of the binary tree is the maximum height between the left and right subtrees plus 1.
Here is an example code snippet in C++ that implements the recursive approach to calculate the height of a binary tree:
struct Node {
int data;
Node* left;
Node* right;
};
int height(Node* root) {
// Base case: empty tree
if (root == nullptr) {
return 0;
}
// Recursive step: calculate height of left and right subtrees
int leftHeight = height(root->left);
int rightHeight = height(root->right);
// Return the maximum height between left and right subtrees, plus 1 for the root
return max(leftHeight, rightHeight) + 1;
}
In this code, we define a Node
struct to represent each node of the binary tree. The height
function takes the root node as input and recursively calculates the height of the tree.
We start by checking if the root is null, indicating an empty tree. In this case, we return 0 as the height.
If the tree is not empty, we recursively calculate the height of the left and right subtrees by calling the height
function on each subtree. We store the heights in variables leftHeight
and rightHeight
.
Finally, we return the maximum height between the left and right subtrees, plus 1 for the root node.
I hope this explanation helps! Let me know if you have any further questions.