Skip to content

Commit 1d067d2

Browse files
committed
[Leo] 7th Week solutions
1 parent bcb2945 commit 1d067d2

File tree

4 files changed

+81
-0
lines changed
  • binary-tree-level-order-traversal
  • lowest-common-ancestor-of-a-binary-search-tree
  • remove-nth-node-from-end-of-list
  • reorder-list

4 files changed

+81
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
3+
if root is None:
4+
return []
5+
6+
queue = deque([root])
7+
return_list = []
8+
9+
while queue:
10+
level_size = len(queue)
11+
current_level = []
12+
13+
for n in range(level_size):
14+
node = queue.popleft()
15+
current_level.append(node.val)
16+
if node.left:
17+
queue.append(node.left)
18+
if node.right:
19+
queue.append(node.right)
20+
21+
return_list.append(current_level)
22+
23+
return return_list
24+
25+
## TC: O(n), SC: O(n)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
3+
4+
while True:
5+
if root.val < min(p.val, q.val):
6+
root = root.right
7+
8+
elif root.val > max(p.val, q.val):
9+
root = root.left
10+
11+
else:
12+
return root
13+
14+
# TC: O(n) where n is height of the tree, SC: O(1)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution:
2+
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
3+
4+
left = right = head
5+
6+
for i in range(n):
7+
right = right.next
8+
9+
if not right: return head.next
10+
11+
while right.next:
12+
left = left.next
13+
right = right.next
14+
15+
left.next = left.next.next ## deleting node
16+
17+
return head
18+
19+
# TC: O(n), SC: O(1)

reorder-list/Leo.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def reorderList(self, head: Optional[ListNode]) -> None:
3+
"""
4+
Do not return anything, modify head in-place instead.
5+
"""
6+
if not head:
7+
return
8+
9+
slow, fast = head, head
10+
while fast and fast.next:
11+
slow, fast = slow.next, fast.next.next
12+
13+
prev, curr = None, slow
14+
15+
while curr:
16+
curr.next, prev, curr = prev, curr, curr.next
17+
18+
first, second = head, prev
19+
while second.next:
20+
first.next, first = second, first.next
21+
second.next, second = first, second.next
22+
23+
## TC: O(n), SC: O(1)

0 commit comments

Comments
 (0)