# 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:
p1 = [p]
q1 = [q]
if p.val != q.val:
return False
while p1 or q1:
pop_nodep = p1.pop(0)
pop_nodeq = q1.pop(0)
if (pop_nodep.left and pop_nodeq.left) or (not pop_nodep.left and not pop_nodeq.left):
if pop_nodep.val != pop_nodeq.val:
return False
else:
if pop_nodep.left:
p1.append(pop_nodep.left)
if pop_nodeq.left:
q1.append(pop_nodeq.left)
else:
return False
if (pop_nodep.right and pop_nodeq.right) or (not pop_nodep.right and not pop_nodeq.right):
if pop_nodep.val != pop_nodeq.val:
return False
else:
if pop_nodep.right:
p1.append(pop_nodep.right)
if pop_nodeq.right:
q1.append(pop_nodeq.right)
else:
return False
elif (not p) and (not q):
return True
else:
return False
return True
思路:其实就是同时遍历两个二叉树,然后判断相应的位置上是否有元素,或者元素是否相等,可以递归遍历也可以用队列来遍历,我这里是模拟队列来进行的,有关于python建立二叉树和二叉树的遍历参考这位小哥的博客。
https://www.cnblogs.com/PrettyTom/p/6677993.html
网友评论