카테고리 없음

[NeetCode/Python] Depth of Binary Tree

빵빵0 2024. 9. 11. 01:13

문제: https://neetcode.io/problems/depth-of-binary-tree

 

NeetCode

 

neetcode.io

 

[내 풀이]

# 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

result = 0

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        global result # 뭐지.. 연속으로 test case 처리하면서 에러나서 급하게 추가
        result = 0

        if root is None:
            return 0

        def search(node: Optional[TreeNode], depth: int) -> int:
            global result
            if node.left is None and node.right is None:
                if result < depth:
                    result = depth
                return

            if node.right is not None:
                search(node.right, depth + 1)

            if node.left is not None:
                search(node.left, depth + 1)
        
        search(root, 1)
        return result

 

[솔루션 풀이 뜯어보기]

# 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

# RECURSIVE DFS
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))


# ITERATIVE DFS
# class Solution:
#     def maxDepth(self, root: Optional[TreeNode]) -> int:
#         stack = [[root, 1]]
#         res = 0

#         while stack:
#             node, depth = stack.pop()

#             if node:
#                 res = max(res, depth)
#                 stack.append([node.left, depth + 1])
#                 stack.append([node.right, depth + 1])
#         return res


# BFS
# class Solution:
#     def maxDepth(self, root: Optional[TreeNode]) -> int:
#         q = deque()
#         if root:
#             q.append(root)

#         level = 0

#         while q:

#             for i in range(len(q)):
#                 node = q.popleft()
#                 if node.left:
#                     q.append(node.left)
#                 if node.right:
#                     q.append(node.right)
#             level += 1
#         return level

 

 

시간 복잡도

추후 작성