-1

Try to make tree , have a some troubles, first it's print function - it's print not integers that i put, but print random numbers;

Another trouble its append child - its works only one times;

Will be happy if you will help me with this task.

And also give some good articles about linked lists, trees on c and c++;


#include <iostream>

#include <stdio.h>

using namespace std;


struct Node
{
    void* m_pPayload;
    Node* m_pParent;
    Node* m_Children;
    
};

struct Person
{
    int m_Id;
};

//typedef bool (*NodeComparator)(void* pValue, void* pPayload);

/*bool Comp(void* pValue, void* pPayload)
{
    Person* pVal = (Person*)pValue;
    Person* pPay = (Person*)pPayload;
    if (pVal->m_Id == pPay->m_Id)
        return true;
    else
        return false;
}
*/

Node* NewNode(void* pPayload)
{
    Node* pNode = new Node;
    pNode->m_pParent = nullptr;
    pNode->m_Children = 0;
    pNode->m_pPayload = pPayload;
    return pNode;
}

Person* NewPerson(int id)
{
    Person* p = new Person;
    p->m_Id = id;
    return p;
}

//Node* FindNode(Node* pParent, Node* m_pPayload, NodeComparator comparator);

void AppendChild(Node* pParent, Node* pNode)
{
    if (pParent->m_Children == NULL)
        pParent->m_Children = pNode;
    
}

void print(Node* head) 
{
    Node* current_node = head;
    while (current_node != NULL) 
    {
        printf("%d\n ", current_node->m_pPayload);
        current_node = current_node->m_Children;
        
    }
}


int main()
{

    Node* T = new Node;
    
    T = NewNode(NewPerson(5));
    
    AppendChild(T, NewNode(NewPerson(11)));
    AppendChild(T, NewNode(NewPerson(15)));
    
    print(T);
    
}


HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • Warning: It looks like you have been learning C with a smattering of C++. You might want to change your reference materials. [Here's a list of good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – user4581301 Jan 25 '21 at 20:37
  • This code exhibits several memory leaks. And there is nothing letting a `Node` know *how many* nodes are in its `m_Children` list (are nodes not allowed to have siblings, or multiple children? That doesn't make this much of a tree). Also, `AppendChild()` is not assigning `pNode->m_Parent`. – Remy Lebeau Jan 25 '21 at 20:41

4 Answers4

1
printf("%d\n ", current_node->m_pPayload)

is incorrect. %d wants an integer and it's being given a pointer. The results will be unusual, and likely appear to be random garbage.

printf("%d\n ", ((Person*)current_node->m_pPayload)->m_Id);
                  ^                                ^
                  |                                Get id from Person
                  treat payload pointer as pointer to Person
                

will solve the immediate problem.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • The better solution to printing a pointer is `%p` instead of `%d`. You are casting a `Person*` to an `int*` and then dereferencing it, which is still undefined behavior. If you are trying to print the person's `m_Id`, use `printf("%d\n ", ((Person*)current_node->m_pPayload)->m_Id)` instead – Remy Lebeau Jan 25 '21 at 20:43
  • you're right. Missed that extra structure. – user4581301 Jan 25 '21 at 20:44
0

Your code actually seems to be pretty messed up with a lot of things going on, here sharing my own commented code from few years back, hope it helps

#include <bits/stdc++.h>
using namespace std;

// Single node representation
struct node {
    int data;
    node *left, *right;
};

// Declaring temp for refference and root to hold  root node
node *root, *temp;

// This function only generates a node and return it to the calling function with data stored in it
node* generateNode(int data){
    temp = new node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}

// This function actually adds node to the tree
node* addNode(int data, node *ptr = root){
    // If the node passed as ptr is NULL
    if(ptr == NULL){
        ptr = generateNode(data);
        return ptr;
    }
    // Condition to check in which side the data will fit in the tree
    else if(ptr->data < data)
        //if its in right, calling this function recursively, with the right part of the tree as the root tree
        ptr->right = addNode(data, ptr->right);
    else
    //In case the data fits in left
        ptr->left = addNode(data, ptr->left);

    //Note: if there is no data in left or roght depending on the data's valid position, this function will get called with NULL as second argument and then the first condition will get triggered

    //returning the tree after appending the child
    return ptr;
}

//Driver function
int main ()
{
    int c, data;
    for (;;){
        cin >> c;
        switch(c){
            case 1:
                cout << "enter data: ";
                cin >> data;
        //Updating root as the tree returned by the addNode function after adding a node
                root = addNode(data);
                break;
            default:
                exit(0);
                break;
        }
    }
        return 0;
}
Kaustubh
  • 373
  • 1
  • 3
  • 14
0

First for printing the node value

Talking about the current mistake that you had committed is in the above code is:

  1. You have not mentioned its pointer to its child (specifically right or left). Due to which it is showing garbage value every time.
    For e.g.: print( node->left);

  2. Since you need to type caste it properly to show the data of data.
    For e.g.: printf("%d\n ", ((Person*)current_node->m_pPayload)->m_Id);

There is a specific direction in which you want to print data. For trees, there are three directions in which you can print the data of the node and they are as follow:

  • Left order or Inorder traversal
  • Preorder traversal
  • Postorder traversal

This can give you better information about traversal.

Secondly for adding the node to a tree
This might help explain it better.

shapiro yaacov
  • 2,308
  • 2
  • 26
  • 39
Gulab_786
  • 31
  • 3
0

Please find below a piece of code that should easily get you started. It compiles and it traverse the tree using recursion.

#include <iostream>
#include <vector>
#include <stdio.h>

using namespace std;


struct Node
{
    int m_Id;
    vector<Node*> m_Children;
    
    Node(const int& id){
       m_Id = id;   
    }
    
    void AppendChild(Node* pNode) {
        m_Children.push_back(pNode);
    }
    
    void Print() {
        printf("%d\n ", m_Id);
    }
    
};

void traverse(Node* head) 
{
    Node* current_node = head;
    current_node->Print();
    for(int i = 0; i<current_node->m_Children.size(); i++) {
        traverse(current_node->m_Children[i]);
    }
}


int main()
{
    Node* T0 = new Node(0);
    
    Node* T10 = new Node(10);
    T10->AppendChild(new Node(20));
    
    Node* T11 = new Node(11);
    
    Node* T12 = new Node(12);
    Node* T22 = new Node(22);
    
    T22->AppendChild(new Node(33));
    T12->AppendChild(T22);
    
    T0->AppendChild(T10);
    T0->AppendChild(T11);
    T0->AppendChild(T12);
    
    traverse(T0);
    
}