Maximum Depth of Binary Tree

2023-12-13 19:49:06

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

文章来源:https://blog.csdn.net/kduduuuw/article/details/134978907
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。