K
K
kopelev20002021-10-06 20:39:22
C++ / C#
kopelev2000, 2021-10-06 20:39:22

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:

Structure

struct Node
{
    char* name; // Имя узла
    Node* son=NULL; // Дочерний узел
    Node* brother=NULL; // Следующий узел на этом же уровне
};
Node* top = NULL;



The tree itself should look something like this:
View

615ddd811b16b643747598.png


A function that I wrote, but it does not allow you to build a tree of arbitrary depth:
add function

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);
        }
    }
}



+How to implement the tree output function?
In this format:
A
B  C  D  E
F G  H I  J  K
...


output function

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

1 answer(s)
A
Alexandroppolus, 2021-10-07
@Alexandroppolus

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 question

Ask a Question

731 491 924 answers to any question