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.