[Leetcode]104. Maximum Depth of Binary Tree

whitehousechef·2025년 5월 25일

https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

initial

pretty starightforward we just increment depth with dfs

sol

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        ans = 0
        def depth(node,cur_depth):
            nonlocal ans 
            if not node: 
                ans = max(ans,cur_depth)
                return
            depth(node.left,cur_depth+1)
            depth(node.right,cur_depth+1)
        depth(root,0)
        return ans

complexity

n time
log n if balanced, n if skewed

0개의 댓글