104. Maximum Depth of Binary Tree

2021. 11. 12. 16:21Leetcode

Description:

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

# 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
'''
[1] bottom-up)

code::
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        if not root.left and not root.right:
            return 1
        left_depth=self.maxDepth(root.left)
        right_depth=self.maxDepth(root.right)
        return max(left_depth,right_depth)+1

-T/C: O(n)
-S/C: O(h)
'''
'''
[2] top-down)

idea::
update depth

code::
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        return self.getDepth(root,0)
        
    
    def getDepth(self,root,depth):
        if not root:
            return depth
        return max(self.getDepth(root.left,depth+1),self.getDepth(root.right,depth+1))
        
-T/C: O(n)
-S/C: O(h)
'''

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

'Leetcode' 카테고리의 다른 글

572. Subtree of Another Tree  (0) 2021.11.15
102. Binary Tree Level Order Traversal  (0) 2021.11.14
100. Same Tree  (0) 2021.11.12
143. Reorder List  (0) 2021.11.12
19. Remove Nth Node From End of List  (0) 2021.11.12