先进行节点的添加,然后进行节点的值的判断,注意初始根节点可能为None,并且最后的时候2个数组的长度还不一样,也需要判断。
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
arr1=[]
arr2=[]
if p==None and q==None:
return True
elif p==None or q==None:
return False
arr1.append(p)
arr2.append(q)
while(len(arr1)!=0 and len(arr2)!=0):
temp1=arr1.pop(0)
temp2=arr2.pop(0)
if temp1.val!=temp2.val:#对于值的判断在这里进行编码
return False
#先添加节点
if temp1.left!=None and temp2.left!=None:
arr1.append(temp1.left)
arr2.append(temp2.left)
elif temp1.left==None and temp2.left==None:
pass
else:
return False
if temp1.right!=None and temp2.right!=None:
arr1.append(temp1.right)
arr2.append(temp2.right)
elif temp1.right==None and temp2.right==None:
pass
else:
return False
if len(arr1)==0 and len(arr2)==0:
return True
else:
return False