题目描述
在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。
如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root,以及树中两个不同节点的值 x 和 y。
只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true。否则,返回 false。
示例 1:
输入:root = [1,2,3,4], x = 4, y = 3
输出:false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cousins-in-binary-tree
解法
这道题解题思路比较简单,递归找目标值和对应的父节点,同时要记录节点深度为了判断是否为堂兄弟节点。
深度是逐步加一。条件的分类讨论种类较多,注意不要遗漏。
/**
* 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 {
public:
void DFS(TreeNode* root,int x,int y,int h){
if(!root) return;
if(root->left&&root->left->val==x){
p1=root;h1=h;
}
if(root->right&&root->right->val==x){
p1=root;h1=h;
}
if(root->left&&root->left->val==y){
p2=root;h2=h;
}
if(root->right&&root->right->val==y){
p2=root;h2=h;
}
DFS(root->left,x,y,h+1);
DFS(root->right,x,y,h+1);
}
bool isCousins(TreeNode* root, int x, int y) {
DFS(root,x,y,0);
return (h1==h2)&&(p1!=p2);
}
private:
TreeNode* p1=NULL;
TreeNode* p2=NULL;
int h1=-1,h2=-1;
};