I am using the Binary Tree implementation of a General Tree, with the general algorithm that, the first son of a node is the “left” and any other siblings are the “right” of the first son.
What I’m trying to answer is, given a node p, how can I find the father of node p?
Here is a node (I’m traversing using a non-recursive way, thus the visited and parent attributes)
struct node {
std::string name;
int sons;
bool visited;
node * first;
node * next;
node * parent;
};
Here is an example:
GeneralTree
A
/|\
B C D
BinaryTree version of GeneralTree
A
/
B
\
C
\
D
So the father node of B, C, and D are all A.
Just follow the parent links until you find a null reference – this happens if you start with
pbeing the root node – or a node with the node you are coming from as its left child.Now
parentcontains the parent node of the node inpornullifpcontains the root node.