[
tree
dfs
bfs
]
BinarySearch 0327 Leaves in Same Level
Problem statement
https://binarysearch.com/problems/Leaves-in-Same-Level/
Solution
Just traverse tree with dfs/bfs and when we have leaf, add its depths to set l. In the end check if it has only one element.
Complexity
It is O(n) for time and O(n) for space.
Code
class Solution:
def solve(self, root):
l = set()
def dfs(node, d):
if not node: return
if not node.left and not node.right:
l.add(d)
dfs(node.left, d + 1)
dfs(node.right, d + 1)
dfs(root, 0)
return len(l) == 1