LeetCode - Day 4

Similar trees

Don't include branches.

# 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 getLeaves(self, root: Optional[TreeNode])->list[int]:
        [v, l, r] = [root.val, root.left, root.right]
        if l is None and r is None:
            return [v]
        elif l is None:
            return self.getLeaves(r)
        elif r is None:
            return self.getLeaves(l)
            return self.getLeaves(l) + self.getLeaves(r)

    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
        return self.getLeaves(root1) == self.getLeaves(root2)

Shuffle the array

Read the definition of n. n is half the length of num.

class Solution:
    def shuffle(self, nums: List[int], n: int) -> List[int]:
        lst = []
        # [2, 3, 5 ,2]
        # n = 2
        for i in range(n):
        return lst

Minimum Sam of Four Digit Number After Splitting Digits

Greedy algorithm; take the smallest number for the most significant digit in each iteration.

class Solution:
    def minimumSum(self, num: int) -> int:
        string = sorted(str(num))
        [new1, new2] = [
            int(string[0])*10 + int(string[2]),
            int(string[1])*10 + int(string[3])
        return new1+new2

Merge Two Sorted Lists

Use a dummy node to solve the problem simply.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        head = ListNode(-1) # Dummy node
        cur = head
        while list1 is not None and list2 is not None:
            if list1.val < list2.val:
                cur.next = list1
                list1 = list1.next
                cur.next = list2
                list2 = list2.next
            cur = cur.next
        if list1 is not None:
            cur.next = list1
        if list2 is not None:
            cur.next = list2
        return head.next