[路飞]_每天刷leetcode_35(相同的树Same Tree)

162 阅读1分钟

相同的树(Same Tree)

LeetCode传送门100. 相同的树

题目

给你两棵二叉树的根节点 pq ,编写一个函数来检验这两棵树是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

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:

Input: p = [1,2,3], q = [1,2,3]
Output: true

Input: p = [1,2], q = [1,null,2]
Output: false

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]. 104<=Node.val<=104-10^4 <= Node.val <= 10^4


思考线


解题思路

要查两棵树是不是相等,最简单的方法是递归遍历两个二叉树的每个节点,若重头到尾都相等则认为相等,否则不相等

代码如下

function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
    if(!p && !q) return true;
    if(!p && q || p && !q) return false;
    if(p.val !==q.val) return false;
    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)

};

这个题也可以用BFS来解题,不过还是上面的递归理解起来最简单,写起来也方便,所以我就不展开了。