Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions invert-binary-tree/yuseok89.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

invert-binary-tree/yuseok89.py
# TC: O(N)
# SC: O(N)
# 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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:

        if not root:
            return None
        else:
            cur_node = TreeNode(root.val)

            cur_node.right = self.invertTree(root.left)
            cur_node.left = self.invertTree(root.right)

            return cur_node
  • 패턴: Binary Search, Depth-First Search, Divide and Conquer
  • 설명: 이 코드는 이진트리의 자식 노드를 서로 바꿔 트리를 반전시키는 재귀적 분할 처리로서, DFS 방식으로 각 서브트리를 처리하며 분할해서 해결하는 패턴을 사용합니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(N) O(n)
Space O(N) O(h)

피드백: 트리의 각 노드를 한 번씩 방문하여 자식 정보를 교환하므로 시간 복잡도는 O(n)이고, 재귀 호출 스택의 깊이에 비례하는 공간 복잡도 O(h)이다.

개선 제안: 현재 구현이 적절해 보입니다.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

앞의 if가 이미 리턴을 하고 있어서 else 를 크게 쓰지 않으셔도 되지 않을까? 라는 생각이 듭니다!
또한 cur_node 를 만들지 않으시고 root를 직접 바꾸셔도 정답처리 되실거에요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# TC: O(N)
# SC: O(N)
# 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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:

if not root:
return None
else:
cur_node = TreeNode(root.val)

cur_node.right = self.invertTree(root.left)
cur_node.left = self.invertTree(root.right)

return cur_node

Loading