题目描述:
给定两个二叉树,编写一个函数来检验它们是否相同。如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 1:
输入: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
输出: true
示例 2:
输入: 1 1
/ \
2 2
[1,2], [1,null,2]
输出: false
示例 3:
输入: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
输出: false
解题思路1:
二叉树的前序遍历与题目中描述的顺序一致,但是目前受限于判断 [1,2]
和 [1,null,2]
。
代码1:
class Solution(object):
def isSameTree(self, p, q):
if p is not None and q is not None:
return True
stack1, output1 = [p], []
stack2, output2 = [q], []
while stack1:
root1 = stack1.pop()
if root1 is not None:
output1.append(root1)
if root1.right is not None:
stack1.append(root1.right)
else:
stack1.append(null)
if root1.left is not None:
stack1.append(root1.left)
else:
stack1.append(null)
while stack2:
root2 = stack2.pop()
if root2 is not None:
output2.append(root2)
if root2.right is not None:
output2.append(root2.right)
else:
stack2.append(null)
if root2.left is not None:
output2.append(root2.left)
else:
stack2.append(null)
if output1 == output2:
return True
return False
解题思路2:
递归思路
代码2:
# 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):
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val: # 这里的写法不能是当二者相等就返回True,因为我们还需要判断接下来的情况
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
题目来源: