给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 1:
输入:p = [1,2,3], q = [1,2,3]
输出:true
示例 2:
输入:p = [1,2], q = [1,null,2]
输出:false
示例 3:
输入:p = [1,2,1], q = [1,1,2]
输出:false
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
# 迭代
stack = [(p,q)]
while stack:
# 首先比较当前的两个节点
a,b = stack.pop()
# 如果a和b为空,继续下一轮比较
if not (a or b):
continue
if a and b and a.val == b.val:
stack.append((a.left, b.left))
stack.append((a.right, b.right))
else:
return False
return True
# 递归
# 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)
37. Leetcode 100. 相同的树 (二叉树-二叉树性质)
最新推荐文章于 2024-11-15 15:03:02 发布