알고리즘/leetcode

104. Maximum Depth of Binary Tree(Easy)

1.5볼트 2023. 2. 16. 18:42
728x90

1.5v

 

본문

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.

 

바이너리 트리의 최대 깊이를 리턴하는 문제 

재귀함수로 한단계씩 내려갈때마다 전역변수 s와 비교하여 최대깊이를 찾는다.

아마도 DFS 알고리즘인가 

# 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:
        global s
        s=0
        def f(root,n):
            global s
            if root==None:
                if s<n:
                    s=n
                return n
            f(root.left,n+1)
            f(root.right,n+1)
        f(root,0)
        return s