Leecode 0100. Same Tree
100. Same Tree
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:
1 | Input: p = [1,2,3], q = [1,2,3] |
Example 2:
1 | Input: p = [1,2], q = [1,null,2] |
Example 3:
1 | Input: p = [1,2,1], q = [1,1,2] |
题目大意
给定两棵二叉树的根节点 p
和 q
,判断这两棵树是否相同。两棵树相同的定义是:结构完全相同,且对应节点的值也相同。
例如:
- 输入两棵结构和节点值均相同的树
[1,2,3]
和[1,2,3]
,返回true
; - 输入结构不同的树
[1,2]
和[1,null,2]
,返回false
。
解题思路
判断两棵树是否相同可通过同步递归遍历实现,核心思路是:
- 若两棵树的当前节点都为空,说明结构相同,返回
true
; - 若其中一棵树的当前节点为空,另一棵不为空,结构不同,返回
false
; - 若两棵树的当前节点值不同,返回
false
; - 递归判断两棵树的左子树和右子树是否分别相同,只有两者都相同时,才返回
true
。
代码实现
1 | /** |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.