75 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* https://leetcode.cn/problems/same-tree/?envType=study-plan-v2&envId=top-interview-150
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
const isSameTree = function (p, q) {
};
/*
如果一个树的字节的和另一个树的子节点相等,只要保证当前节点相等的话,
那么整棵树也就相等了
*/
function f1(p, q) {
if (p === null && q === null) return true;
if (p && q && p.val === q.val) {
return f1(p.left, q.left) && f1(p.right, q.right);
}
return false;
}
/*
优化判断分支
*/
function f2(p, q) {
// 如果两个节点都为空,返回 true表示当前节点相等
if (!p && !q) return true;
// 如果其中一个节点为空,或者节点值不相等,返回 false
if (!p || !q || p.val !== q.val) return false;
// 递归检查左右子树
return f1(p.left, q.left) && f1(p.right, q.right);
}
/*
通过BFS来判断两个数每一层对应节点的值是否相等
*/
function f3(p, q) {
// 初步判断,如果两个树的根节点有一个为空,另一个不为空,则返回 false
if (!p && !q) return true;
if (!p || !q) return false;
// 上面这两个判断可有可无
const queue = [p, q]; // 队列存储两个树的根节点
while (queue.length > 0) {
const node1 = queue.shift();
const node2 = queue.shift();
if (!node1 && !node2) continue; // 如果两个节点都为空
// 如果两个节点值不同,或者其中一个为空,直接返回 false
if (!node1 || !node2 || node1.val !== node2.val) {
return false;
}
// 将左子节点和右子节点加入队列
queue.push(node1.left, node2.left);
queue.push(node1.right, node2.right);
}
return true;
}