⬅ Previous Topic
Zigzag Traversal of a Binary TreeNext Topic ⮕
Diagonal Traversal of a Binary Tree⬅ Previous Topic
Zigzag Traversal of a Binary TreeNext Topic ⮕
Diagonal Traversal of a Binary Treeclass 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))
⬅ Previous Topic
Zigzag Traversal of a Binary TreeNext Topic ⮕
Diagonal Traversal of a Binary TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.