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.