Search code examples
c++pointerstreebinary-treeparent

c++ how to assign a pointer to a parent in a binary tree


i'm confused on how you initialize the m_parent to point to the node above the child.

    class Node
{
public:
    Node(string city);
    ~Node();
    string m_city;
    int m_parent_distance;
    Node *m_left;
    Node *m_right;
    Node *m_parent;
};
Node *m_root;
//void test_print(string target, Node *cur_root);
Node * find_node(Node *m_root, string target);

this is the node constructor

    Stree::Node::Node(string city)
{
    m_city = city;
    m_left = NULL;
    m_right = NULL;
    //what do i do with m_parent??
    m_parent_distance = 0;
}

Solution

  • Pass the parent as a parameter to your constructor, and initialize it from there:

    class Node
    {
    public:
        Node(string city, Node *parent);
        ~Node();
        string m_city;
        int m_parent_distance;
        Node *m_left;
        Node *m_right;
        Node *m_parent;
    };
    
    Stree::Node::Node(string city, Node *parent)
        : m_city(city),
          m_left(NULL),
          m_right(NULL),
          m_parent(parent),
          m_parent_distance(0)
    {
    }
    

    By the way, you should use an initializer list (like I wrote above) rather than assignments in the constructor (like the code you showed us).