Given the roots of two binary trees
p
and q
, 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: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false
Constraints:
The number of nodes in both trees is in the range
[0, 100]
.
-10<sup>4</sup> <= Node.val <= 10<sup>4</sup>
题目大意:
判断二叉树是否相等
解题思路:
类似于Leetcode 101 Symmetric Tree但稍简单, easy题
解题步骤:
N/A
注意事项:
Python代码:
1
2
3
4
5
6def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if not p or not q:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
算法分析:
时间复杂度为O(n)
,空间复杂度O(1)