二叉树的堂兄弟节点-c语言
在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。
如果二叉树的两个节点深度相同,但 父节点不同 ,则它们是一对堂兄弟节点。
我们给出了具有唯一值的二叉树的根节点 root ,以及树中两个不同节点的值 x 和 y 。
只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true 。否则,返回 false。
对于这题我使用的是递归,先轮番找到节点的深度,之后进行比较,但是比较的同时,我们要判断一下是否是兄弟节点,即可。
算法实现图下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int f(struct TreeNode* root, int value, int h,int value2){
int a=-1, b=-1;
if(root){
if(root->val==value){
return h;
}
else {
if(root->left&&root->right){
if(root->left->val==value&&root->right->val==value2){
return -2;
}
}
if(root->left){
a=f(root->left,value,h+1,value2);
}
if(root->right){
b=f(root->right,value,h+1,value2);
}
}
}
if(a==-2||b==-2){
return -1;
}
if(a!=-1)return a;
else if(b!=-1)return b;
else return -1;
}
bool isCousins(struct TreeNode* root, int x, int y){
int hx,hy;
// struct TreeNode *hxnode=NULL,*hynode=NULL;
hx=f(root,x,1,y);
hy=f(root,y,1,x);
printf("%d %d",hx,hy);
if(hx==hy) return true;
else return false;
}
这个算法取得了还不错的结果。