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.因为是二叉树,所以总可以写成队列的形式进行比较。