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:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
if (p==None and q==None): #如果都是空,是相同的
return True
elif ((p!=None and q==None) or (p==None and q!=None)):#如果有一个是空,另一个不是空,则不同
return False
else: #进入此条件的是两个都不为空,所以必有值和左右节点,虽然有可能是空,然后递归
return((p.val==q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right, q.right)))
282

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



