目录结构
1.题目
在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。
如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root,以及树中两个不同节点的值 x 和 y。
只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true。否则,返回 false。
示例:
输入:root = [1,2,3,4], x = 4, y = 3
输出:false
输入:root = [1,2,3,null,4,null,5], x = 5, y = 4
输出:true
输入:root = [1,2,3,null,4], x = 2, y = 3
输出:false
提示:
- 二叉树的节点数介于
2
到100
之间。 - 每个节点的值都是唯一的、范围为
1
到100
的整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cousins-in-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
遍历分别记录x和y的高度及父节点,再判断即可。
public class Solution993 {
@Test
public void test993() {
TreeNode root = new TreeNode(34, new TreeNode(23, new TreeNode(15), null),
new TreeNode(98, null, new TreeNode(115)));
System.out.println(isCousins(root, 15, 98));
}
int[] depth = new int[2];
int[] parent = new int[2];
public boolean isCousins(TreeNode root, int x, int y) {
if (root.val == x || root.val == y) {
return false;
}
dfs(root, null, 0, x, y);
return depth[0] == depth[1] && parent[0] != parent[1];
}
public void dfs(TreeNode root, TreeNode par, int d, int x, int y) {
if (root != null) {
if (root.val == x) {
depth[0] = d;
parent[0] = par.val;
}
if (root.val == y) {
depth[1] = d;
parent[1] = par.val;
}
d++;
dfs(root.left, root, d, x, y);
dfs(root.right, root, d, x, y);
}
}
}
- 时间复杂度:
- 空间复杂度: