In this particular problem I was doing Maximum Depth of Binary Tree, the tree's depth is defined as: "A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node." I did this question using DFS first, where I calculated the depth as follows:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left, right)+1
Then I did this problem again using BFS by calculating the number of levels in the tree and this solution was also correct, which lead to the question if depth = # of levels in the tree.
BFS Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
q = deque()
q.append(root)
depth = 0
while q:
size = len(q)
for i in range(size):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
depth+=1
return depth