LeetCode 每日一题 :993. 二叉树的堂兄弟节点
分析:
判断两个节点是否为堂兄弟节点就需要判断它们的父节点是否不同以及它们的高度是否相同。那么问题就变为了求两个节点的父节点及其高度。使用深度优先遍历这棵树即可。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int x;
TreeNode xParent;
int xDepth;
int y;
TreeNode yParent;
int yDepth;
public boolean isCousins(TreeNode root, int x, int y) {
this.x = x;
this.y = y;
dfs(root, null, 0);
return xDepth == yDepth && xParent != yParent;
}
public void dfs(TreeNode root, TreeNode parent, int depth) {
if (root == null) {
return ;
}
if (root.val == this.x) {
this.xDepth = depth;
this.xParent = parent;
}
if (root.val == this.y) {
this.yDepth = depth;
this.yParent = parent;
}
dfs(root.left, root, depth + 1);
dfs(root.right, root, depth + 1);
}
}