Как посчитать количество листьев в n-арном дереве
Добавлено: 09 мар 2010, 17:21
Как задать n-арное дерево и посчитать количество листьев на языке С++
форум программистов
https://www.developing.ru/
Код: Выделить всё
struct CNode
{
int nData; // some node data
CNode* pChildren; // pointer to array of child nodes
};
Код: Выделить всё
int GetLeafCount(CNode* pNode)
{
int nLeafCount = 0;
if (pNode->pChildren)
{
for (int i = 0; i < N; ++i)
{
nLeafCount += GetLeafCount(&pNode->pChildren[i]);
}
}
else
{
++nLeafCount;
}
return nLeafCount;
}
Код: Выделить всё
struct CNode
{
int nData; // some node data
CNode** pChildren; // pointer to array of child nodes
};
Код: Выделить всё
CNode node;
// children array creation
node.pChildren = new CNode [N];
// children array freeing
delete [] node.pChildren;
Код: Выделить всё
nLeafCount += GetLeafCount(&pNode->pChildren[i]);
Код: Выделить всё
// Derevo.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
struct CNode {
int number;
char deti;
int data; // some node data
CNode* pChildren; // pointer to array of child nodes
};
int N,i;
int nn = 0;
int count = 0;
int Zapolnenie(CNode* pNode)
{
pNode->number = nn++;
cout << "Vi v vershine " << pNode->number << "\nDannie uzla ";
cin >> pNode->data;
if(pNode->deti == 1) {
cout << "Skoka detey? ";
int l; cin >> l;
if(l > 0) {
pNode->pChildren = new CNode[l];
pNode->deti = 2;
for(int qq = 0; qq < l; qq++) {(pNode->pChildren[qq]).deti = 1; }
Zapolnenie(&pNode->pChildren[0]);
}
if(l == 0) count++;
}
if(pNode->deti == 2) { for (int i = 1; i < N; i++)
if(&pNode->pChildren[i])
{Zapolnenie(&pNode->pChildren[i]); }
}
return(0);
}
int main() {
cout << "Vvedite N> "; cin >> N;
int j;
CNode* perv=new CNode[1];
perv->deti = 1;
Zapolnenie(perv);
cout << count;
getch();
}
Код: Выделить всё
// Derevo.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
struct CNode
{
int number; // number of node
int data; // some node data
unsigned int nChildCount; // amount of chidren
CNode* pChildren; // pointer to array of child nodes
};
int nn = 0;
int count = 0;
void Zapolnenie(CNode* pNode)
{
pNode->number = nn++;
cout << "Vi v vershine " << pNode->number << "\nDannie uzla ";
cin >> pNode->data;
cout << "Skoka detey? ";
unsigned int l; cin >> l;
if (l > 0)
{
pNode->nChildCount = l;
pNode->pChildren = new CNode[l];
for (int qq = 0; qq < l; ++qq)
{
Zapolnenie(&pNode->pChildren[qq]);
}
}
else
{
pNode->nChildCount = 0;
pNode->pChildren = NULL;
++count;
}
}
void Udalenie(CNode* pNode)
{
if (pNode->nChildCount > 0)
{
for (int qq = 0; qq < pNode->nChildCount; ++qq)
{
Udalenie(&pNode->pChildren[qq]);
}
delete [] pNode->pChildren;
}
}
int main()
{
CNode node;
Zapolnenie(&node);
cout << "Kolichestvo list'ev: " << count;
getch();
Udalenie(&node);
return 0;
}