maxpayne
maxpayne

Reputation: 1111

How to move from Child to Parent in a tree structure?

struct node
{
    int data;
    node *child;
    node *sibling
};

I want to have a loop that moves from child to parent. If the root of a tree has 5 children then starts from last child to root. meaning that the loop should move in a reverse way.

In fact, it could be easy if I have an array of children, but what if I just have a child parent relationship, in that case, each child has a parent, So is it possible that I go from child to parents until I get to root.

Upvotes: 1

Views: 3512

Answers (1)

Peter mCnerd
Peter mCnerd

Reputation: 36

You need a parent pointer to move directly from child to parent in a loop. I find this works.

struct node{
    int value;
    node * parent;
    node ** childArray;
    int NumberOfChildren;
}

You set parent to null on the root node, and set the childArray pointer to null on the leaf (final) node.

When you want to move through the tree you use a node*.

e.g.

node * PCurrentNode = &MyNode;
PCurrentNode = MyNode->Parent;//Move Up
PCurrentNode = MyNode->ChildNodes[5]//Move to the 5th child node

You can avoid using parent pointers if you start at the root node and recurse down as you simply recurse up to get to the parent node.

Upvotes: 2

Related Questions