LeetCode | 0100. Same Tree 相同的樹【Python】

LeetCode 0100. Same Tree 相同的樹【Easy】【Python】【二叉樹】

Problem

LeetCode

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

問題

力扣

給定兩個二叉樹,編寫一個函數來檢驗它們是否相同。

如果兩個樹在結構上相同,並且節點具有相同的值,則認爲它們是相同的。

示例 1:

輸入:       1         1
          / \       / \
         2   3     2   3
        [1,2,3],   [1,2,3]
輸出: true

示例 2:

輸入:      1          1
          /           \
         2             2
        [1,2],     [1,null,2]
輸出: false

示例 3:

輸入:       1         1
          / \       / \
         2   1     1   2
        [1,2,1],   [1,1,2]
輸出: false

思路

二叉樹

Python3代碼
# 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:
        # 兩棵樹都爲空
        if not p and not q:
            return True
        # 一棵樹爲空,另一棵不爲空
        elif not p or not q:
            return False
        # 兩棵樹都非空,但節點值不同
        elif p.val != q.val:
            return False
        # 分別判斷左子樹和右子樹
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

GitHub鏈接

Python

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章