Thursday 20 September, 2012




Q) Given a Binary Tree where each node has one extra pointer along with left and right pointers, write a function to populate this extra pointer for all nodes with inorder successor of that node.

struct node
{
int data;
struct node *left;
struct node *right;
struct node *next;
}
Initially, all next pointers have NULL values. We should populate these next pointers so that they point to inorder successor.

Ans)
We can do reverse inorder traversal so that we'll first traverse inorder succesor of each node before traversing the node.

So following will do:
1. Traverse Right sub-tree
2. Traverse the node. Save this node for storing as inorder successor of next node
3. Traverse Left sub-tree

void inorder_succ(node *ptr)
{
static node *tmp = NULL;
if (!ptr)
     return;

inorder_succ(ptr->right);
ptr->next = tmp;
tmp = ptr;
inorder_succ(ptr->left);
}

No comments:

Post a Comment