问题描述
给定一个二叉树和一个节点 x
,找到和 x
有相同深度的节点 y
,使得 x
和 y
在树中不同子树。如果只有一个这样的节点 y
,则返回它。如果有两个这样的节点 y
,返回值未定义。
注意: 这个问题是路径和问题的一个变种,需要我们找到与给定节点在同一深度但不在同一路径上的节点。
输入: 二叉树的根节点 root
和节点 x
的值 x
。
输出: 满足条件的节点 y
的值。
解法一
解题思路:
我们需要遍历二叉树,找到 x
的深度和 x
的父节点。然后,我们再次遍历二叉树,找到与 x
有相同深度且不是 x
子树的节点 y
。
/*
* @lc app=leetcode.cn id=993 lang=javascript
*
* [993] Cousins in Binary Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val=0, left=null, right=null)
*/
/**
* @param {TreeNode} root
* @param {number} x
* @param {number} y
* @return {boolean}
*/
var isCousins = function(root, x, y) {
const xDepth = findDepth(root, null, x, 0);
const yDepth = findDepth(root, null, y, 0);
const xParent = findParent(root, x);
const yParent = findParent(root, y);
return xDepth === yDepth && xParent !== yParent;
};
function findDepth(node, parent, val, depth) {
if (node === null) return -1;
if (node.val === val) return depth;
const left = findDepth(node.left, node, val, depth + 1);
if (left !== -1) return left;
return findDepth(node.right, node, val, depth + 1);
}
function findParent(node, val) {
if (node === null || node.val === val) return null;
if (node.left && findParent(node.left, val) !== null ||
node.right && findParent(node.right, val) !== null) {
return node;
}
return null;
}
// @lc code=end