⬅ Previous Topic
Check if a Binary Tree is a Sum TreeNext Topic ⮕
Lowest Common Ancestor (LCA) in a Binary Tree⬅ Previous Topic
Check if a Binary Tree is a Sum TreeNext Topic ⮕
Lowest Common Ancestor (LCA) in a Binary Treetrue
.queue
and enqueue the root node along with its level (0
).leafLevel
to -1
to record the level of the first encountered leaf node.leafLevel
is -1
, set it to the current level.leafLevel
, return false
.true
as all leaves are at the same level.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from collections import deque
def are_leaves_at_same_level(root):
if not root:
return True
queue = deque([(root, 0)])
leaf_level = -1
while queue:
node, level = queue.popleft()
if not node.left and not node.right:
if leaf_level == -1:
leaf_level = level
elif level != leaf_level:
return False
if node.left:
queue.append((node.left, level + 1))
if node.right:
queue.append((node.right, level + 1))
return True
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / \ \
# 4 5 6
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, None, TreeNode(6)))
print(are_leaves_at_same_level(root))
⬅ Previous Topic
Check if a Binary Tree is a Sum TreeNext Topic ⮕
Lowest Common Ancestor (LCA) in 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.