C++中打印给定节点在二叉树中的堂兄弟节点
二叉树是一种特殊的树,其每个节点最多有两个子节点。因此,每个节点要么是叶节点,要么有一个或两个子节点。
示例:

在这个问题中,我们给定一个二叉树和树的一个节点,我们必须找到该节点的堂兄弟节点。二叉树中不应打印兄弟节点。
让我们举个例子:

对于上面的二叉树,堂兄弟节点是 5。
为了使概念更清晰,让我们描述一下堂兄弟节点。在二叉树中,如果两个节点位于二叉树的同一层(深度),但没有相同的父节点,则称这两个节点为堂兄弟节点。
现在,让我们为这个问题创建一个解决方案。
在这里,我们必须打印节点同一层的所有节点,即所有与根节点距离相同的节点。但是,我们必须排除与该节点本身具有相同父节点的节点。为此,我们将首先找到节点的层级,然后打印所有节点(节点本身和具有相同父节点的节点除外)。
示例
现在,让我们根据此逻辑创建一个程序:
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *left, *right;
};
Node *newNode(int item){
Node *temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
int levelOfNode(Node *root, Node *node, int level){
if (root == NULL)
return 0;
if (root == node)
return level;
int downlevel = levelOfNode(root->left,
node, level + 1);
if (downlevel != 0)
return downlevel;
return levelOfNode(root->right, node, level + 1);
}
void printCousin(Node* root, Node *node, int level){
if (root == NULL || level < 2)
return;
if (level == 2){
if (root->left == node || root->right == node)
return;
if (root->left)
cout << root->left->data << " ";
if (root->right)
cout << root->right->data;
}
else if (level > 2){
printCousin(root->left, node, level - 1);
printCousin(root->right, node, level - 1);
}
}
void cousinNode(Node *root, Node *node){
int level = levelOfNode(root, node, 1);
printCousin(root, node, level);
}
int main(){
Node *root = newNode(11);
root->left = newNode(15);
root->right = newNode(4);
root->left->left = newNode(3);
root->left->right = newNode(7);
root->left->right->right = newNode(9);
root->right->left = newNode(17);
root->right->right = newNode(8);
root->right->left->right = newNode(5);
cout<<”The cousin nodes are : \t”
cousinNode(root, root->right->right);
return 0;
}输出
The cousin nodes are : 3 7
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP