题目描述:
解:
因为需要知道父节点和深度,所以需要用dfs或bfs的方式去遍历,选择dfs的原因是比bfs更好写…
class Solution {
int x; //记录x
int xDepth;
TreeNode xParent;
boolean xFound = false;
int y; //记录y
int yDepth;
TreeNode yParent;
boolean yFound = false;
private void dfs(TreeNode root,int depth,TreeNode parent) {
if(root == null) {
return;
}
if(xFound && yFound) { //都找到了就可以返回了
return;
}
if(root.val == x) {
xDepth = depth;
xParent = parent;
xFound = true;
} else if(root.val == y) {
yDepth = depth;
yParent = parent;
yFound = true;
}
if(xFound && yFound) {
return;
}
dfs(root.left,depth+1,root);
dfs(root.right, depth + 1, root);
}
public boolean isCousins(TreeNode root, int x, int y) {
this.x = x;
this.y = y;
dfs(root,0,null);
return xDepth == yDepth && xParent != yParent;
}
}