LeetCode题解——二叉树的堂兄弟节点
- 题目介绍
- 解题思路
- 这题考察的就是树的遍历,其中带有2个条件遍历树
- 第一个条件记录下x和y出现的深度
- 第二个条件记录下x和y的父节点
- 当父节点不同xy深度相等就是满足题目的堂兄弟节点
- 代码示例
/**
* 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 xdep;
int ydep;
TreeNode *xparent;
TreeNode *yparent;
public:
void tree_search(TreeNode* root, int &x,int &y,int count){
if(root == NULL || (xdep > 0 &&count > xdep) || (ydep > 0 &&count > ydep)) {
return;
}
count ++;
if(root->left != NULL){
if(root->left->val == x){
xdep = count+1;
xparent = root;
}else if(root->left->val == y) {
ydep = count+1;
yparent = root;
}
tree_search(root->left,x,y,count);
}
if(root->right != NULL){
if(root->right->val == x){
xdep = count+1;
xparent = root;
}else if(root->right->val == y) {
ydep = count+1;
yparent = root;
}
tree_search(root->right,x,y,count);
}
}
bool isCousins(TreeNode* root, int x, int y) {
if(root->left == nullptr || root->right == nullptr){
return false;
}
xdep = -1,ydep = -1;
int count = -1;
xparent = yparent = nullptr;
tree_search(root,x,y,count);
if(xparent != yparent && xdep == ydep){
return true;
}else{
return false;
}
}
};