美文网首页
python实现leetcode之100. 相同的树

python实现leetcode之100. 相同的树

作者: 深圳都这么冷 | 来源:发表于2021-09-23 00:01 被阅读0次

解题思路

左右子树递归相同,并且根节点值相同,就是相同,否则不同

100. 相同的树

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p is None and q is None: return True
        if p is None: return False
        if q is None: return False
        if p.val != q.val: return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
效果图

相关文章

网友评论

      本文标题:python实现leetcode之100. 相同的树

      本文链接:https://www.haomeiwen.com/subject/tihmgltx.html