题目
在二叉树中,根节点位于深度 0
处,每个深度为 k
的节点的子节点位于深度 k+1
处。
如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root
,以及树中两个不同节点的值 x
和 y
。
只有与值 x
和 y
对应的节点是堂兄弟节点时,才返回 true
。否则,返回 false
。
示例
示例1
输入:root = [1,2,3,4], x = 4, y = 3
输出:false
示例2
输入:root = [1,2,3,null,4,null,5], x = 5, y = 4
输出:true
题目分析
我使用层序遍历解决这道题,使用层序遍历的好处是:1、方便的找到父亲节点;2、方便的求指定结点的深度。
我们来整理一下遍历过程:
- 如果根节点等于
x
或y
,则直接返回false
; - 使用层序遍历来遍历这个树,获得指定结点的头结点和深度。
层序遍历过程:
q.push(root);
int count = 1;
while (!q.empty()) {
int len = q.size();
count++;
while (len--){
TreeNode* temp = q.front();
q.pop();
if (temp->left) {
if (temp->left->val == x) {
head = temp;
return count;
}
q.push(temp->left);
}
if (temp->right) {
if (temp->right->val == x){
head = temp;
return count;
}
q.push(temp->right);
}
}
}
题目解答
class Solution {
public:
int depth(TreeNode* root, int x, TreeNode* &head){
if (!root) return -1;
if (root->val == x) return 1;
queue<TreeNode*> q;
q.push(root);
int count = 1;
while (!q.empty()){
int len = q.size();
count++;
while (len--){
TreeNode* temp = q.front();
q.pop();
if (temp->left){
if (temp->left->val == x) {
head = temp;
return count;
}
q.push(temp->left);
}
if (temp->right){
if (temp->right->val == x){
head = temp;
return count;
}
q.push(temp->right);
}
}
}
return -1;
}
bool isCousins(TreeNode* root, int x, int y) {
if (!root) return false;
if (root->val == x || root->val == y) return false;
TreeNode* head_x;
TreeNode* head_y;
int h_x = depth(root, x, head_x);
int h_y = depth(root, y, head_y);
// printf("%d %d\n%d %d ", h_x, h_y, head_x->val, head_y->val);
if (h_x != h_y) return false;
else {
if (head_x->val == head_y->val) return false;
return true;
}
}
};