Algorithm Steps
- If the tree is empty, the height is
0
. - Recursively compute the height of the left subtree.
- Recursively compute the height of the right subtree.
- The height of the tree is
1 + max(height(left), height(right))
.
Find Height of a Binary Tree - Code Examples Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def findHeight(root):
if not root:
return 0
return 1 + max(findHeight(root.left), findHeight(root.right))
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
print("Height of the tree:", findHeight(root))