LeetCode题解:993. 二叉树的堂兄弟节点,BFS,JavaScript,详细注释-CSDN博客
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
原题链接
https://.cn/problems/cousins-in-binary-tree/
解题思路
- 使用队列进行BFS搜索同时保存每个节点以及其深度和父节点信息。
- 当搜索到
x
和y
时对比深度和父节点如果满足要求则表示找到了堂兄弟节点。
/**
* @param {TreeNode} root
* @param {number} x
* @param {number} y
* @return {boolean}
*/
var isCousins = function (root, x, y) {
// 使用队列进行BFS搜索每个元素保存的值是当前节点、节点深度、父节点
let queue = [[root, 1, null]]
// 保存搜索到的x和y节点信息
let result = []
// 不断搜索直到队列被清空表示完成了对二叉树的搜索。
while (queue.length) {
// 将队列元素出队获取相关信息
const [node, depth, parent] = queue.shift()
// 当查找到x或y的值时将相应的信息保存到result
if (node.val === x || node.val === y) {
result.push([node, depth, parent])
}
// 如果result的长度为2表示已查找到x和y
if (result.length === 2) {
// 如果x和y的深度相等父节点不同表示找到了堂兄弟节点
if (result[0][1] === result[1][1] && result[0][2] !== result[1][2]) {
return true
}
return false
}
// 将当前节点的左右子节点入队继续搜索
node.left && queue.push([node.left, depth + 1, node])
node.right && queue.push([node.right, depth + 1, node])
}
};
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |