leetcode-4.27[83. 刪除排序鏈表中的重複元素、100. 相同的樹](python解法)

題目1

在這裏插入圖片描述

題解1

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if head is None:
            return None
        pointer = head
        # 因爲pointer和pointer.next要比較,所以這裏必須作爲條件
        while pointer and pointer.next: 
            if pointer.val == pointer.next.val:
                pointer.next = pointer.next.next
            else:
                pointer = pointer.next
        return head

題目2

在這裏插入圖片描述

題解2

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 
        # 都爲同返回True
        if p is None and q is None:
            return True
        # 如果一個爲None,一個不爲None,結果不同返回False
        if p is None or q is None:
            return False
        if p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章