Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
思路1:递归
对于任何两棵相同的树,根节点值相同,且两个左右子树也相同。故我们只需要递归判断p的左子树和q的左子树是否相等,p的右子树和q的右子树是否相等,递归的退出条件为p与q均等于null或其中之一为null
class Solution(object):
def isSameTree(self, p, q):
if p is None and q is None:
return True
elif p is not None and q is not None:
return p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
else:
return False
思路2: 迭代遍历
对于两棵相同的树,我们在遍历的时候把其当做完全二叉树进行遍历,对于空节点,用#号替代,遍历的结果是相同的。
class Solution(object):
def isSameTree(self, p, q):
p = self.pre_trival(p)
q = self.pre_trival(q)
return p == q
def pre_trival(self,p):
queue = [p]
result = []
while len(queue):
p = queue.pop(0)
if p:
result.append(p.val)
if p.left
queue.append(p.left)
queue.append(p.right)
else:
result.append("#")
return result
def post_trival(self, p):
if p:
p.status = 1
stack = [p]
result = []
while len(stack):
while p:
p =p.left
if p:
p.status = 1
stack.append(p)
p = stack.pop(-1)
if p and p.status == 1:
right = p.right
p.status = 0
stack.append(p)
if right:
right.status = 1
stack.append(right)
elif p is None:
result.append("#")
else:
result.append(p.val)
return result