0
votes

The question is, given a binary tree, where each node has four pieces of data: left, right ,data and an empty pointer parent, we have to update the tree such that the parent pointer of each node points to its parent (the root parent pointer will naturally point to a NULL value). Now how do I do this? I tried a post-order traversal like this:

last = None
def mypostorder(root):
    if root:
      mypostorder(root.left)
      mypostorder(root.right)
      if last:
        last.parent = root
      last = root

But obviously it is not working, and I know why, after updating the parent pointer of a left-child, it sets it as last, so next time when it visits the right-child (its sibling), it sets its parent to the left-child. How to tweak it to get the correct result? Is it possible to do it iteratively as well, using a stack, may be?

2

2 Answers

3
votes
void setParent(node * ptr,node * parent_ptr)
{

if(ptr==NULL)
return;

ptr->parent=parent_ptr; //update the parent for the current node

parent_ptr=ptr; //now update the parent pointer

setParent(ptr->left,parent_ptr); //repeat the process for children

setParent(ptr->right,parent_ptr);
}

Initial Call : setParent(root,NULL);

2
votes

You have it going the wrong way. I think your solution would make the parent of a node point to its child

Give this a try:

def myPostOrder(root, par=None):
    if root:
        root.parent = par
        myPostOrder(root.left, root)
        myPostOrder(root.right, root)