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.