Algorithm Steps
- Given a binary tree, if the tree is empty, it is considered balanced.
- Recursively compute the height of the left and right subtrees.
- If the absolute difference between the left and right subtree heights is more than 1, the tree is not balanced.
- Recursively check that both the left subtree and the right subtree are balanced.
- If all checks pass, the binary tree is balanced.
Check if a Binary Tree is Balanced - 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 isBalanced(root):
def height(node):
if not node:
return 0
return max(height(node.left), height(node.right)) + 1
if not root:
return True
leftHeight = height(root.left)
rightHeight = height(root.right)
if abs(leftHeight - rightHeight) > 1:
return False
return isBalanced(root.left) and isBalanced(root.right)
# Example usage:
if __name__ == '__main__':
# Construct a binary tree:
# 1
# / \
# 2 3
# /
# 4
root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))
print(isBalanced(root))