Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 84c4944

Browse files
committed
add 21.py
1 parent 350d98c commit 84c4944

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

21.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from typing import Optional
2+
3+
# Definition for singly-linked list.
4+
class ListNode:
5+
def __init__(self, val=0, next=None):
6+
self.val = val
7+
self.next = next
8+
9+
10+
class Solution:
11+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
12+
13+
# create sentinel node
14+
s = ListNode(0, None)
15+
previous = s
16+
17+
while list1 is not None and list2 is not None:
18+
# compare value at l1 vs value at l2
19+
# whichever is smaller that's where we point previous, and step that list
20+
# essentially prev keeps track of the new list
21+
22+
if list1.val <= list2.val:
23+
previous.next = list1
24+
list1 = list1.next
25+
else:
26+
previous.next = list2
27+
list2 = list2.next
28+
29+
previous = previous.next
30+
31+
# the while loop only runs while l1 or lx2 are not None
32+
33+
# since lists can be diffent sizes,
34+
# when we've reached the end for one we can point
35+
# the merged list to the non-null list
36+
previous.next = list1 or list2
37+
38+
return s.next
39+
40+
41+
42+
l1 = ListNode(val=1, next=ListNode(val=2, next=ListNode(val=3, next=None)))
43+
l2 = ListNode(val=4, next=ListNode(val=5, next=None))
44+
45+
s = Solution()
46+
s.mergeTwoLists(list1=l1, list2=l2)

226.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Definition for a binary tree node.
2+
class TreeNode:
3+
def __init__(self, val=0, left=None, right=None):
4+
self.val = val
5+
self.left = left
6+
self.right = right
7+
8+
9+
10+
class Solution:
11+
def invertTree(self, root) -> Optional[TreeNode]:
12+
# do if root is not null
13+
if root:
14+
self.invertTree(root.left)
15+
self.invertTree(root.right)
16+
17+
root.left, root.right = root.right, root.left
18+
19+
return root
20+
21+
22+
if '__name__' == '__main__':
23+
root = TreeNode(1)
24+
root.left = TreeNode(2)
25+
root.right = TreeNode(3)
26+
root.left.left = TreeNode(4)
27+
root.left.right = TreeNode(5)
28+
root.right.left = TreeNode(6)
29+
root.right.right = TreeNode(7)
30+
31+
sol = Solution()
32+
sol.invertTree(root)

0 commit comments

Comments
 (0)