What is the Height of Binary Tree (BT)?
The height of the Binary Tree is the number of edges from the root node to the deepest leaf node.
The height of the tree is the same as the height of the root node.
In the above binary tree,
What is the maximum and minimum height of the binary tree having n elements?
The height of the binary tree can always be in the range of log(n) to (n-1).
For example, the binary tree having eight nodes can have minimum height log(8)=3 and maximum height 8-1=7 nodes.
You can find the height of the binary tree using recursion technique.
Using recursion, it is simple. The height of any node (root) is one plus maximum of the height of the left and right node.
class node: def __init__(self, val, left=None, right=None): self.left=left self.val=val self.right=right def height(root): if root: return 1+max(height(root.left), height(root.right)) else: return -1 root=node(4) root.left=node(1) root.right=node(5) root.left.left=node(7) root.left.right=node(3) root.right.right=node(6) print("Height of the Binary Tree: ", height(root))
Height of the Binary Tree: 2
If there is no right or left child to the root node, the height of the BT will be zero.
You can write a program to find the height of the Binary Tree in any programming languages like C/C++, Java using the same logic.
Knowing the height of the binary tree is very important to solve many of the binary tree problems in competitive programming.