如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
解法1.先序遍历
思路: 套用先序遍历模板,将二叉树存为目标数组,对比两个数组是否相同
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
def preorder(root):
if not root:
return [None]
else:
return [root.val] + preorder(root.left) + preorder(root.right)
return preorder(p) == preorder(q)
解法2.递归求解
思路:如果两个二叉树相同,则他们的根相同,左右孩子对应相同。递归调用,对比子树。**
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if not p and not q:
return True
elif not p or not q:
return False
else:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)