title | description | keywords | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
100. 相同的树 |
LeetCode,100. 相同的树,相同的树,Same Tree,解题思路,树,深度优先搜索,广度优先搜索,二叉树 |
|
🟢 Easy 🔖 树
深度优先搜索
广度优先搜索
二叉树
🔗 力扣
LeetCode
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^4 <= Node.val <= 10^4
这一题要求判断两颗树是否是完全相等的。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
递归判断即可。
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function (p, q) {
if (!p && !q) return true;
if (p && q && p.val == q.val) {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
return false;
};