建设公司官网流程seo扣费系统
原题链接:
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])}
};