题目
题目来源:力扣(LeetCode)
在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。
如果二叉树的两个节点深度相同,但 父节点不同 ,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root ,以及树中两个不同节点的值 x 和 y 。
只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true 。否则,返回 false。
示例 1:
输入:root = [1,2,3,4], x = 4, y = 3
输出:false
示例 2:
输入:root = [1,2,3,null,4,null,5], x = 5, y = 4
输出:true
示例 3:
输入:root = [1,2,3,null,4], x = 2, y = 3
输出:false
思路分析
深度优先搜索
- 要想判断两个节点 x 和 y 是否为堂兄弟节点,我们就需要求出这两个节点分别的「深度」以及「父节 点」。
- 因此,我们可以从根节点开始,对树进行一次遍历,在遍历的过程中维护「深度」以及「父节点」这 两个信息。
- 当我们遍历到 x 或 y 节点时,就将信息记录下来;当这两个节点都遍历完成了以后,我们就可以退出 遍历的过程,判断它们是否为堂兄弟节点了。
- 在使用深度优先搜索时,我们只需要在深度优先搜索的递归函数中增加表示「深度」以及「父节点」的两个参数即可。
var isCousins = function (root, x, y) {// x_parent x 的父节点// x_depth x 的深度// x_found 标记是否找到了 xlet x_parent = null, x_depth = null, x_found = false;// y_parent y 的父节点// y_depth y 的深度// y_found 标记是否找到了 ylet y_parent = null, y_depth = null, y_found = false;const dfs = (node, depth, parent) => {if (!node) { // 节点为 null 的时候,退出递归函数return;}if (node.val === x) {// 找到了 x 节点,把它的父节点和深度记录下来[x_parent, x_depth, x_found] = [parent, depth, true];} else if (node.val === y) {// 找到了 y 节点,把它的父节点和深度记录下来[y_parent, y_depth, y_found] = [parent, depth, true];}// 如果两个节点都找到了,就可以提前退出遍历// 即使不提前退出,对最坏情况下的时间复杂度也不会有影响if (x_found && y_found) {return;}dfs(node.left, depth + 1, node);if (x_found && y_found) {return;}dfs(node.right, depth + 1, node);}dfs(root, 0, null);// 如果确定他俩是堂兄弟节点了,直接返回,不用再往下遍历了return x_depth === y_depth && x_parent !== y_parent;};
广度优先搜索
在广度优先搜索的过程中,每当我们从队首取出一个节点,它就会作为「父节点」,将最多两个子节点放入队尾。因此,除了节点以外,我们只需要在队列中额外存储「深度」的信息即可。
var isCousins = function(root, x, y) {// x_parent x 的父节点// x_depth x 的深度// x_found 标记是否找到了 xlet x_parent = null, x_depth = null, x_found = false;// y_parent y 的父节点// y_depth y 的深度// y_found 标记是否找到了 ylet y_parent = null, y_depth = null, y_found = false;// 用来判断是否遍历到 x 或 y 的辅助函数const update = (node, parent, depth) => {if (node.val === x) {// 找到了 x 节点,把它的父节点和深度记录下来[x_parent, x_depth, x_found] = [parent, depth, true];} else if (node.val === y) {// 找到了 y 节点,把它的父节点和深度记录下来[y_parent, y_depth, y_found] = [parent, depth, true];}}// 队列存储节点及深度let q = [[root, 0]];update(root, null, 0);while (q.length) {// 从队列中拿出一个节点,const [node, depth] = q.shift()if (node.left){q.push([node.left, depth + 1]);update(node.left, node, depth + 1);}if (node.right) {q.push([node.right, depth + 1]);update(node.right, node, depth + 1);}if (x_found && y_found) {break;}}// 如果确定他俩是堂兄弟节点了,直接返回,不用再往下遍历了return x_depth === y_depth && x_parent !== y_parent;};
