2018-12-28

LeetCode 100. Same Tree.jpg

LeetCode 100. Same Tree

Description

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

描述

  • 此題目是給定兩棵樹,判斷兩個(gè)樹是否相等.
  • 兩顆樹相等意味著結(jié)構(gòu),值要完全一樣.
  • 此題目使用遞歸求解.
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2018-12-28 19:06:08
# @Last Modified by:   何睿
# @Last Modified time: 2018-12-28 19:12:16

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        # 如果第一個(gè)樹和第二個(gè)樹都是空,說明兩個(gè)樹是相等的,返回True.
        if not p and not q:
            return True
        # 如果有一個(gè)數(shù)為空另一個(gè)樹不為空,說明兩個(gè)樹一定不會相等
        if not p or not q:
            return False
        # 如果兩個(gè)樹的節(jié)點(diǎn)值不相等,則兩條樹不會相等,返回False
        if p.val != q.val:
            return False
        # 如果以上條件都通過了,說明兩個(gè)樹的當(dāng)前節(jié)點(diǎn)相等
        # 我們分別判斷這兩條樹的左子樹是否相等,右子樹是否相等
        left = self.isSameTree(p.left,q.left)
        right = self.isSameTree(p.right,q.right)
        # 返回最終結(jié)果
        return left and right

源代碼文件在這里.
?本文首發(fā)于何睿的博客,歡迎轉(zhuǎn)載,轉(zhuǎn)載需保留文章來源,作者信息和本聲明.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容