Q100 Same Tree

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
解题思路:

根据相同树的定义,递归比较左子树与右子树的结点是否相等。注意这里的相同树必须满足左右子树对应结点的数字完全相同才可以。

Python实现:
# 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, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p == None and q == None:
            return True
        if p != None and q != None and p.val == q.val:
            return Solution.isSameTree(self, p.left, q.left) and Solution.isSameTree(self, p.right, q.right)
        else:
            return False
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,453评论 0 10
  • 十年前的今天, 我开车驶过大桥, 那座铺满我们脚印的桥, 苦着脸的天像被谁打得片片淤紫, 风看着两只揉着伤囗的小鸟...
    晏萍阅读 369评论 38 42
  • Maya是一位小姑娘,她只有米粒儿那么大,真的,只有米粒儿那么大,她生活在另外一维度里,只是喜欢跑到人类的圈圈里玩...
    半山桃源阅读 390评论 0 1
  • 《三国演义 》讲述的是从汉灵帝元年(184)黄巾军起义,到晋武帝太康元年(280年)间,魏、吴、蜀、三国灭亡,晋武...
    勇敢的追求阅读 587评论 0 1
  • 今天为大家介绍一些适合炎热季节吃的日本沙拉及寿司饭的做法,每道菜都简单且有高大上的感觉,可以款待朋友时炫耀一番哦。...
    Ragny瑞格妮阅读 1,326评论 2 2