DEV Community

Cover image for Leetcode Solutions: Maximum Depth of Binary Tree
SalahElhossiny
SalahElhossiny

Posted on

Leetcode Solutions: Maximum Depth of Binary Tree

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.


class Solution(object):
    def maxDepth(self, root):
        stack = [[root, 0]]
        res = 0

        while stack:
            node, depth = stack.pop()
            res = max(res, depth)
            if node:
                stack.append([node.left, depth + 1])
                stack.append([node.right, depth + 1])


        return res


Enter fullscreen mode Exit fullscreen mode

Top comments (0)