Leetcode 104. Maximum depth of binary tree (파이썬, python3)

진이·2022년 11월 19일
0

파이썬

목록 보기
2/7

1.BFS를 사용한 풀이

# 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:
        if not root:
            return 0
            
        queue = collections.deque([root])
        depth = 0
        
        while queue:
            depth += 1
            for _ in range(len(queue)):
                cur_root = queue.popleft()
                if cur_root.left:
                    queue.append(cur_root.left)
                if cur_root.right:
                    queue.append(cur_root.right)
        return depth

2.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:
    	if not root:
        	return 0
            
        ans = [-1]
        def DFS(cur_root, depth):
            if cur_root.left:
                DFS(cur_root.left, depth + 1)
            if cur_root.right:
                DFS(cur_root.right, depth + 1)
            else:
                ans[0] = max(ans[0], depth)
                return
                
        DFS(root, 1)
        return ans[0]
profile
최선을 다할게

0개의 댓글