1int height(Node* root)
2{
3 // Base case: empty tree has height 0
4 if (root == nullptr)
5 return 0;
6
7 // recur for left and right subtree and consider maximum depth
8 return 1 + max(height(root->left), height(root->right));
9}
10
1// finding height of a binary tree in c++.
2int maxDepth(node* node)
3{
4 if (node == NULL)
5 return 0;
6 else
7 {
8 /* compute the depth of each subtree */
9 int lDepth = maxDepth(node->left);
10 int rDepth = maxDepth(node->right);
11
12 /* use the larger one */
13 if (lDepth > rDepth)
14 return(lDepth + 1);
15 else return(rDepth + 1);
16 }
17}
1# define a Class Tree, to intiate the binary tree
2class TreeNode:
3 def __init__(self, val):
4 self.val = val
5 self.left = None
6 self.right = None
7
8def height(root):
9
10 # Check if the binary tree is empty
11 if root is None:
12 # If TRUE return 0
13 return 0
14 # Recursively call height of each node
15 leftAns = height(root.left)
16 rightAns = height(root.right)
17
18 # Return max(leftHeight, rightHeight) at each iteration
19 return max(leftAns, rightAns) + 1
20
21# Test the algorithm
22root = TreeNode(1)
23root.left = TreeNode(2)
24root.right = TreeNode(3)
25root.left.left = TreeNode(4)
26
27print("Height of the binary tree is: " + str(height(root)))
28