判断二叉树是否是同一颗树。
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
分析
递归解决。
# 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 and q:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return p == q
# BFS #
> 可以使用一个queue来存储子节点,每遍历一个节点,就把子节点(n1,n2)存到queue,然后每次从queue去一对节点来比较。
# 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):
queue = [(p,q)]
while queue:
n1,n2 = queue.pop(0)
if n1 and n2:
if n1.val != n2.val:
return False
queue += [(n1.left, n2.left), (n1.right, n2.right)]
elif n1 or n2:
return False
else:
continue
return True
近期评论