LeetCode 100 Same Tree (Python)

Posted by 小明MaxMing on July 13, 2020

题目

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.

解题思路

比较当前节点的值是否相同,递归比较两个子树

代码

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        if not p or not q:
            return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅