问题描述
简要思路
递归查找 x , y 的父节点并层层记录深度,按照题意对照深度和父节点值即可。
0ms 代码。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int xf, yf, xdepth, ydepth;
void findDepth(TreeNode* root, int x, int y, int father, int depth){
if(root == NULL) return;
if(root->val == x){
xf = father;
xdepth = depth;
}
else if(root->val == y){
yf = father;
ydepth = depth;
}
else{
depth++;
findDepth(root->left, x, y, root->val, depth);
findDepth(root->right, x, y, root->val, depth);
}
}
bool isCousins(TreeNode* root, int x, int y) {
findDepth(root->left, x, y, root->val, 1);
findDepth(root->right, x, y, root->val, 1);
return (xf != yf && xdepth ==ydepth);
}
};