题目描述:
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
思路:
树的题目很多都是利用递归完成,所以第一想法就是递归。首先判断当前节点是否都为空,都为空则直接输出True。若不为空,那么判断当前节点的值和当前节点左右节点的值是否相等。这些条件同时满足则直接返回True。
代码:
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if p is None and q is None: return True
if 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