Leetcode练习(Python):树类:第100题:相同的树:给定两个二叉树,编写一个函数来检验它们是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

题目:

相同的树:给定两个二叉树,编写一个函数来检验它们是否相同。  如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

思路:

递归秒解,思路也简单。

程序:

# 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 q:
            return False
        if p and not q:
            return False
        if not p and not q:
            return True
        if p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

  

posted on 2020-05-18 20:03  桌子哥  阅读(455)  评论(0编辑  收藏  举报