Maximum Depth of Binary Tree

Problem

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.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Intuition

The goal is to find the maximum depth of a binary tree, which is the length of the longest path from the root to a leaf node. The depth of a node is the number of edges on the longest path from the node to a leaf. Intuitively, we can use a depth-first or breadth-first traversal to explore the tree and keep track of the depth at each node.

Approach

Stack-based Depth-First Traversal:

Use a stack to perform a depth-first traversal of the binary tree.
The stack stores pairs of nodes and their corresponding depths.
Start with the root node and depth 1.
Pop nodes from the stack, update the maximum depth, and push the left and right children (if any) with incremented depths.
Continue until the stack is empty.
Update Maximum Depth:

At each step, update the maximum depth encountered so far.
Return Maximum Depth:

After the traversal is complete, return the maximum depth as the result.

Complexity

  • Time complexity:

The time complexity is O(n), where n is the number of nodes in the binary tree. Each node is visited exactly once, and the depth update operation takes constant time.

  • Space complexity:

The space complexity is O(h), where h is the height of the binary tree. In the worst case, the stack will have a maximum size equal to the height of the tree. For a balanced binary tree, the height is O(log n), resulting in a space complexity of O(log n). However, in the worst case of an unbalanced tree, the height could be O(n), resulting in a space complexity of O(n).

Code

# 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:
        stack = [[root , 1]]
        res = 0

        while stack:
            node , depth = stack.pop()

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

        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值