Leetcode 104: Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree 

  • Total Accepted: 184446
  • Total Submissions: 369369
  • Difficulty: Easy
  • Contributors: Admin

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

Code (BFS)

from collections import *
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0

        q = deque([(root, 1)])
        max_lvl = 1

        while q:
            node, lvl = q.popleft()
            max_lvl = max(max_lvl, lvl)
            if node.left is not None: 
                q.append((node.left, lvl+1))
            if node.right is not None:
                q.append((node.right, lvl+1))
            
        return max_lvl

 

Code (DFS)

from collections import *
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return max(self.maxDepth(root.left), self.maxDepth(root.right))+1 if root is not None else 0

 

 

 

Leave a comment

Your email address will not be published. Required fields are marked *