104. Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree

Leetcode Blind 75

9th Sept 2022 ~ Dion Pinto

Description

Given the root of a binary tree, return its maximum depth. 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. (Problem)

Code

We can find the max subarray by 2 common methods DFS, BFS. Following is the DFS (recursive) approach.


				
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def maxDepth(self, root: Optional[TreeNode]) -> int:
                if not root:
                    return 0
                
                return(1 + max(self.maxDepth(root.left),self.maxDepth(root.right)))
							
			

BFS (queue) approach.


				
    from collections import deque
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def maxDepth(self, root: Optional[TreeNode]) -> int:
            if not root:
                return 0
            level=0
            q = deque([root])
            
            while q:
                
                for i in range(len(q)):
                    node = q.popleft()
                
                    if node:
                        if node.left:
                            q.append(node.left)
                        if node.right:
                            q.append(node.right)
                        
                level+=1
            return level
							
			

Time Complexity => o(n)

Space Complexity => o(n) (height of tree, since tree is not balanced its o(n))

Back