Tensorum
YouTubeसीखना शुरू करें
LeetCode 104 · DFS Basics

Maximum Depth of Binary Tree

LeetCode 104 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

depth = 1 + max(depth(left), depth(right)).

आसानTreeDepth-First SearchBreadth-First SearchBinary Tree

मैंने Maximum Depth of Binary Tree (LeetCode 104) ऐसे हल किया — DFS Basics पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

A tree's depth is one more than the deeper of its two subtrees; an empty tree has depth 0.

Approach

  1. 1

    Empty → 0.

  2. 2

    Recurse on both children.

  3. 3

    Return 1 + the larger.

मैंने कैसे हल किया

Post-order recursionPythonO(n) time · O(h) space
# 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:
        def dfs(node):
            if node==None:
                return 0
            left = max(0,dfs(node.left))
            right = max(0,dfs(node.right))
            return 1+max(left,right)
        return dfs(root)
स्टेप-थ्रू लोड हो रहा है…

Maximum Depth of Binary Tree — अक्सर पूछे जाने वाले प्रश्न

Maximum Depth of Binary Tree के पीछे intuition क्या है?

A tree's depth is one more than the deeper of its two subtrees; an empty tree has depth 0.

Maximum Depth of Binary Tree (LeetCode 104) कैसे हल करें?

1. Empty → 0. 2. Recurse on both children. 3. Return 1 + the larger.

Maximum Depth of Binary Tree की time और space complexity क्या है?

Time: O(n)। Space: O(h)। (Accepted approach: Post-order recursion।)

Maximum Depth of Binary Tree में आम गलतियाँ क्या हैं?

BFS by levels gives the same answer iteratively.