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.