深圳西乡 网站建设,荔浦火车站建设在哪里,开阿里巴巴网站建设流程,做网站价格和配置原题链接#xff1a; https://leetcode.cn/problems/cousins-in-binary-tree/
解题思路#xff1a;
使用队列进行BFS搜索#xff0c;同时保存每个节点#xff0c;以及其深度和父节点信息。当搜索到x和y时#xff0c;对比深度和父节点#xff0c;如果满足要求#xff0…原题链接 https://leetcode.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的值时将相应的信息保存到resultif (node.val x || node.val y) {result.push([node, depth, parent])}// 如果result的长度为2表示已查找到x和yif (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])}
};