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?
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: