yeenow123
yeenow123

Reputation: 836

Finding father of node in Binary Tree converted from General Tree

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.

Upvotes: 2

Views: 1230

Answers (1)

Daniel Brückner
Daniel Brückner

Reputation: 59645

Just follow the parent links until you find a null reference - this happens if you start with p being the root node - or a node with the node you are coming from as its left child.

var current = p;
var parent = current.parent;

while ((parent != null) && (current != parent.left))
{
    current = parent;
    parent = current.parent;
}

Now parent contains the parent node of the node in p or null if pcontains the root node.

Upvotes: 3

Related Questions