Check if All Leaf Nodes are at the Same Level in a Binary Tree
⬅ Previous TopicCheck if a Binary Tree is a Sum Tree
Next Topic ⮕Lowest Common Ancestor (LCA) in a Binary Tree
Next Topic ⮕Lowest Common Ancestor (LCA) in a Binary Tree
Solution
Algorithm Steps
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
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))