Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Code Block
languagepy
titleMerge Two Sorted Lists
linenumberstrue
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1:
            return l2
        if not l2:
            return l1
        
        p1=l1
        p2=l2
        
        head = None
        tail = None
        
        while p1 and p2:
            if p1.val <= p2.val:
                node = ListNode(p1.val)
                p1 = p1.next
            else:
                node = ListNode(p2.val)
                p2 = p2.next
            
            if tail:
                tail.next = node
            else:
                head = node
            tail = node
                
        while p1:
            node = ListNode(p1.val)
            tail.next = node
            tail = node
            p1 = p1.next

        while p2:
            node = ListNode(p2.val)
            tail.next = node
            tail = node
            p2 = p2.next

        return head
Code Block
languagepy
titleallPathsSourceTarget
linenumberstrue
class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        target = len(graph) - 1
        all_path = []
        path = []

        def dfs(v):
            if v == target:
                path.append(v)
                all_path.append(path[:])
                return

            path.append(v)
            for w in graph[v]:
                if not w in path:
                    dfs(w)
                path.pop()

        dfs(0)
        return all_path
Code Block
titlesame tree
linenumberstrue
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        def dfs(p: TreeNode, q: TreeNode):
            if not p and not q:
                return True
            if not p or not q:
                return False

            if p.val != q.val:
                return False

            return dfs(p.left, q.left) and dfs(p.right, q.right)

        return dfs(p, q)