100. 相同的树
letcode 100.
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
递归
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if not q or not p or p.val != q.val:
return False
return self.isSameTree(p.right, q.right) and self.isSameTree(p.left, q.left)
迭代
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
stack = [(q, p)]
while stack:
a, b = stack.pop()
if not a and not 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

912

被折叠的 条评论
为什么被折叠?



