在本文中,我们将提供完整的信息来确定 n 叉树中给定节点的兄弟节点数量。我们需要使用用户给定的 key 值找到该节点的兄弟节点;如果不是,则输出-1。我们只能使用一种方法 -
简单方法
在这种方法中,我们将遍历所有节点并检查子节点是否与用户具有相同的值。如果存在,我们回答子节点的数量 - 1(给定值)。
示例
#include
using namespace std;
class Node { // structure of nodes of our tree.
public:
int key;
vector child;
Node(int data){
key = data;
}
};
int main(){
// Building The Tree
Node* Base = new Node(50);
(Base->child).push_back(new Node(2));
(Base->child).push_back(new Node(30));
(Base->child).push_back(new Node(14));
(Base->child).push_back(new Node(60));
(Base->child[0]->child).push_back(new Node(15));
(Base->child[0]->child).push_back(new Node(25));
(Base->child[0]->child[1]->child).push_back(new Node(70));
(Base->child[0]->child[1]->child).push_back(new Node(100));
(Base->child[1]->child).push_back(new Node(6));
(Base->child[1]->child).push_back(new Node(1));
(Base->child[2]->child).push_back(new Node(7));
(Base->child[2]->child[0]->child).push_back(new Node(17));
(Base->child[2]->child[0]->child).push_back(new Node(99));
(Base->child[2]->child[0]->child).push_back(new Node(27));
(Base->child[3]->child).push_back(new Node(16));
int x = 30;
queue q;
q.push(Base);
bool flag = 0;
int answer = -1;
if(Base -> key != x){
while(!q.empty()){
auto parent = q.front();
q.pop();
for(int i = 0; i child.size(); i++){
if(parent -> child[i] -> key == x){
answer = parent -> child.size() - 1;
flag = 1;
break;
}
q.push(parent -> child[i]);
}
if(flag)
break;
}
cout