Is the depth of a binary tree same as the total number of levels in the binary tree?

Viewed 64

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
1 Answers

In short: Yes. There isn't much more to this.

BFS advances level by level, which is apparent in your code. While DFS tries each path up to the maximum depth possible and then comes back and tries other paths.

Related