View Single Post
  #3 (permalink)  
Old 06-24-2008, 09:27 PM
dargueta dargueta is online now
Guru
 
Join Date: Oct 2007
Age: 18
Posts: 858
Last Blog:
Programs Under the Hoo...
Credits: 0
Rep Power: 13
dargueta is a jewel in the roughdargueta is a jewel in the roughdargueta is a jewel in the roughdargueta is a jewel in the rough
Default Re: Question: "Binary Tree" only with parent pointer

Since both children have the same parent (eventually), just compare the parents recursively, like so:

C Code:
  1. struct Node
  2. {
  3.     Node  *parent;
  4.     int  value;
  5. };
  6.  
  7. Node *getParent(Node *childLeft, Node *childRight)
  8. {
  9.     Node *currLeft = childLeft;
  10.     Node *currRight = childRight;
  11.  
  12.     while(true)
  13.     {
  14.         //check for nulls
  15.         if((currLeft == NULL)||(currRight = NULL))
  16.             return NULL;
  17.         //check to see if the parents are the same
  18.         //if so, return the parent.
  19.         if(currLeft->parent == currRight->parent)
  20.             return currLeft->parent;
  21.         //parents aren't the same, continue up the tree
  22.         currLeft = currLeft->parent;
  23.         currRight = currRight->parent;
  24.     }
  25. }

Last edited by dargueta; 06-24-2008 at 09:27 PM. Reason: Fixed formatting
Reply With Quote