Answer the question
In order to leave comments, you need to log in
Need to build a general tree, how to add nodes and display the tree on the screen?
How should the algorithm for adding a node, displaying it on the screen for a general tree (in C/C++) look like? It is necessary to implement for this structure:
struct Node
{
char* name; // Имя узла
Node* son=NULL; // Дочерний узел
Node* brother=NULL; // Следующий узел на этом же уровне
};
Node* top = NULL;
void Add(Node*& top, char* Key, char* AddKey)
{
if (top == NULL)
{
top = new Node;
top->name = Key;
top->brother = NULL;
top->son = NULL;
return;
}
else
{
if (top->name == AddKey && top->son == NULL) // добавить сына, если нет сыновей у корня
{
Add(top->son, Key, AddKey);
return;
}
if (top->name == AddKey && top->son != NULL)
{
if (top->son->brother == NULL) // добавить брата сыну, если есть такой
{
Add(top->son->brother, Key, AddKey);
return;
}
if (top->son->brother != NULL && top->son->brother->brother == NULL) // добавить брата, если есть уже 1 брат
{
Add(top->son->brother->brother, Key, AddKey);
return;
}
if (top->son->brother != NULL && top->son->brother->brother != NULL) // добавить брата, если уже есть 2 брата
{
Add(top->son->brother->brother->brother, Key, AddKey);
return;
}
}
if (top->name != AddKey && top->son != NULL)
{
Add(top->son->son, Key, AddKey);
}
}
}
A
B C D E
F G H I J K
...
void PrintTree(Node* top) {
if (top == NULL) return;
cout << top->name << endl;
PrintTree(top->brother);
PrintTree(top->son);
}
Answer the question
In order to leave comments, you need to log in
the task of printing a tree is not devoid of aesthetics. I wrote down on js, translate it into pluses, I think it’s not very difficult
https://jsfiddle.net/uos2jqy7/1/ (see in the console)
adding nodes is also not difficult, only there should be several functions: add a root node, add a son /brother for some node.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question