给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

Given the roots of two binary trees p and q, 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: p = [1,2,3], q = [1,2,3]

file

Output: true

Example 2:
Input: p = [1,2], q = [1,null,2]

file

Output: false

Example 3:
Input: p = [1,2,1], q = [1,1,2]

file

Output: false

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -10^4 <= Node.val <= 10^4

Solution in python:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if p == None and q == None:
            return True
        elif (p and q == None) or (p == None and q):
            return False
        elif p.val != q.val:
            return False
        else:
            left_p, right_p = p.left, p.right
            left_q, right_q = q.left, q.right
            return self.isSameTree(left_p, left_q) and self.isSameTree(right_p, right_q)
最后修改日期: 2021年1月6日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。