一、题目
在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。
如果二叉树的两个节点深度相同,但 父节点不同 ,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root ,以及树中两个不同节点的值 x 和 y 。
只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true 。否则,返回 false。
二、思路
根据题意,只需要找到x和y节点的深度和父节点,进行比较判断即可。
遍历二叉树的方式有深度遍历和广度遍历,我们只选用一种作为编程演示即可,本题较为简单,可自行实现另一种方法。两个问题:
1、如何记录父节点?
直接拿着当前节点去判断节点的左右孩子节点是否为x或y,如果是,这样当前节点就是父节点,直接记录。
2、如何记录深度?
使用一个变量depth,在迭代的时候,每迭代一次,传参+1即可。
三、代码
class Solution {
private TreeNode xF = null, yF = null;
private int xDepth = 0, yDepth = 0;
public boolean isCousins(TreeNode root, int x, int y) {
dfs(root, x, y, 1);
if (xDepth == yDepth) {
return (xF != null) && (yF != null) && (xF != yF);
}
return false;
}
private void dfs(TreeNode root, int x, int y, int depth) {
if (root == null) {
return ;
}
if (root.left != null) {
if (root.left.val == x) {
xDepth = depth;
xF = root;
return;
}
if (root.left.val == y) {
yDepth = depth;
yF = root;
return;
}
}
if (root.right != null) {
if (root.right.val == x) {
xDepth = depth;
xF = root;
return;
}
if (root.right.val == y) {
yDepth = depth;
yF = root;
return;
}
}
dfs(root.left, x, y, depth+1);
dfs(root.right, x, y, depth+1);
}
}
时间复杂度为O(n),空间复杂度为O(h),h为树的高度。