LeetCode 100. Same Tree

简介: 此题目是给定两棵树,判断两个树是否相等.

v2-00c3cd8c16205161fd8db4d70fa3d61c_1440w.jpg

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


描述



  • 此题目是给定两棵树,判断两个树是否相等.
  • 两颗树相等意味着结构,值要完全一样.
  • 此题目使用递归求解.


# -*- 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
        """
        # 如果第一个树和第二个树都是空,说明两个树是相等的,返回True.
        if not p and not q:
            return True
        # 如果有一个数为空另一个树不为空,说明两个树一定不会相等
        if not p or not q:
            return False
        # 如果两个树的节点值不相等,则两条树不会相等,返回False
        if p.val != q.val:
            return False
        # 如果以上条件都通过了,说明两个树的当前节点相等
        # 我们分别判断这两条树的左子树是否相等,右子树是否相等
        left = self.isSameTree(p.left,q.left)
        right = self.isSameTree(p.right,q.right)
        # 返回最终结果
        return left and right


源代码文件在这里.


目录
相关文章
[LeetCode]--100. Same Tree
Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. pub
887 0
LeetCode 100 Same Tree(相同树判断)(二叉树、递归、栈和队列、深搜和宽搜)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50496422 翻译 给定两个二叉树,写一个函数检查他们是否相等。
772 0
【LeetCode从零单排】No100 Same Tree && No101 Symmetric Tree
题目 1.same tree Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value
872 0
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3

热门文章

最新文章