Maximum Depth of Binary Tree
LeetCode 104 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
depth = 1 + max(depth(left), depth(right)).
मी 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
Empty → 0.
- 2
Recurse on both children.
- 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.