leetcode python3 简单题100. Same Tree

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第一百题

(1)题目
英文:
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.

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/same-tree

(2)解法
① 使用递归判断每个节点是否相同即可
第一种:(耗时: 44ms,内存:13.7M)

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

第二种:(耗时: 52ms,内存:13.8M)

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

② 非递归,使用队列迭代
(耗时: 48ms,内存:13.5M)

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        def check(p, q):
            if p == None and q == None: return True
            if p == None or q == None: return False
            if p.val != q.val: return False
            return True
        
        que = [(p, q)]
        while que:
            p, q = que.pop(0) 
            if not check(p, q):
                return False
            if p:
                que.append((p.left, q.left))    
                que.append((p.right, q.right))
        return True

注意:
1.que.pop(0)可以改为que.pop(-1)
2.if p:可以改为if q:
3.因为是二叉树,所以总可以写成队列的形式进行比较。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值