Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
25 changes: 25 additions & 0 deletions maximum-depth-of-binary-tree/thispath98.py
Copy link
Contributor

Choose a reason for hiding this comment

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

공간 복잡도를 answer 변수 사용으로 O(1) 으로 잡아주셨는데, 해당 문제 풀이를 DFS 를 사용하셔서 제 생각에는 DFS의 호출에 따라 그만큼 스택이 쌓여서 Tree의 높이인 h만큼이 소요되여 O(h)가 될 것 같습니다. 한번 더 확인 해주시면 감사하겠습니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

재귀 호출 스택도 공간 복잡도에 포함시켜야 하는군요. 감사합니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
"""
Intuition:
왼쪽 자식과 오른쪽 자식에 대해 depth를 증가시키며 재귀하고,
둘 중 큰 값을 반환한다.

Time Complexity:
O(N):
모든 노드에 대해 재귀적으로 호출하므로 O(N)이다.

Space Complexity:
O(1):
answer 변수만 사용하므로 O(1)이다.
"""
def get_depth(node, depth):
if not node:
return depth

left = get_depth(node.left, depth + 1)
right = get_depth(node.right, depth + 1)
return max(left, right)

answer = get_depth(root, 0)
return answer
31 changes: 31 additions & 0 deletions reorder-list/thispath98.py
Copy link
Contributor

Choose a reason for hiding this comment

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

nodes 배열에 모든 노드를 담아 O(n) 으로 풀이해 주셨네요!
해당 문제의 경우 LinkedList의 특성을 활용하는 문제로 O(1) 의 공간 복잡도로 문제 풀이가 가능하실 것 같습니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Intuition:
nodes 리스트에 모든 노드를 저장한다.
현재 노드가 -i - 1번째 노드일 때,
현재 노드의 next는 head의 next로 설정하고,
head의 next는 현재 노드로 설정한다.
이후 마지막에 중간에 있는 노드를 None으로 설정한다.

Time Complexity:
O(N):
모든 노드를 순회하므로 O(N)이다.

Space Complexity:
O(N):
모든 노드를 nodes 리스트에 저장하므로 O(N)이다.
"""
nodes = []
node = head
while node:
nodes.append(node)
node = node.next

for i in range((len(nodes) - 1) // 2):
cur = nodes[-i - 1]
cur.next = head.next
head.next = cur
head = cur.next

nodes[len(nodes) // 2].next = None