分析:dfs
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int xparent, xdepth, yparent, ydepth;
public:
void dfs(TreeNode* node, int depth, int x, int y, int parent){
if(node == nullptr){
return;
}
if(node->val == x){
xparent = parent;
xdepth = depth;
}
else if(node->val == y){
yparent = parent;
ydepth = depth;
}
else{
dfs(node->left, depth + 1, x, y, node->val);
dfs(node->right, depth + 1, x, y, node->val);
}
}
bool isCousins(TreeNode* root, int x, int y) {
dfs(root->left, 1, x, y, root->val);
dfs(root->right, 1, x, y, root->val);
if((xparent != yparent)&&(xdepth == ydepth)){
return true;
}
else{
return false;
}
}
};