#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
#ifndef NTREE
#define NTREE
class Ntree;
class Node{
public:
char key[100];
Node *next[10];
Node(char *key, int maxNode){
strcpy(this->key, key);
for(int i=0; i<10; i++)
next[i] = NULL;
}
Node(){
for(int i=0; i<10; i++)
next[i] = NULL;
memset(key, 100, sizeof(char));
}
friend class Ntree;
};
class NTree{
static int maxNode;
public:
Node *head;
NTree(int m){
maxNode = m;
}
static Node *newNode(char *key){
Node *n = new Node(key, maxNode);
return n;
}
void count(Node *p, int &max, int &cur){
cur++;
if(max < cur)
max = cur;
for(int i=0; i<maxNode; i++){
if(p->next[i] != NULL){
count(p->next[i], max, cur);
cur--;
}
}
//return max;
}
operator int(){
int max = 0, cur = 0;
count(head, max, cur);
return max;
}
void DFS(Node *p){
if(p==NULL)
return;
for(int i=0; i<maxNode; i++){
DFS(p->next[i]);
}
cout<<p->key<<" ";
}
void DFS(){
DFS(head);
}
void BFS(){
queue<Node *> q;
q.push(head);
while(!q.empty()){
Node *n = q.front();
q.pop();
if(n==NULL)
continue;
cout<<n->key<<" ";
for(int i=0; i<maxNode; i++)
q.push(n->next[i]);
}
}
};
#endif
int NTree::maxNode = 4;
int main(){
NTree tree(4);
tree.head = NTree::newNode("Bird");
tree.head->next[0] = NTree::newNode("Carnivorous");
tree.head->next[1] = NTree::newNode("Herbivorous");
tree.head->next[0]->next[0] = NTree::newNode("Scanvengers");
tree.head->next[0]->next[1] = NTree::newNode("Predators");
cout<<"Total Height : "<<int(tree) <<"\n\n";
cout<<"\nDFS Traversal\n\n";
tree.DFS();
cout<<"\n\n\nBFS Traversal\n\n";
tree.BFS();
return 0;
}
A Complete Class with newNode function, DFS Traversal, BFS Traversal and an example
Compile using GCC without need of any other libraries
Compile using GCC without need of any other libraries
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.