본문 바로가기
Algorithm/파이썬 알고리즘 인터뷰

[트리] 이진 트리의 최대 깊이

by 밤초록 2022. 5. 4.
104 | Maximum Depth of Binary Tree
https://leetcode.com/problems/maximum-depth-of-binary-tree/

 

 

 

이상 코드

 

 

import collections


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None:
            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)
        # BFS 반복 횟수 == 깊이
        return depth

 

 

  • 반복문을 이용한 BFS
  • queue를 한 번 돌 때 depth += 1  / 계속 호출되는 것이 아니라 간단했음
반응형

댓글