Construct Binary Tree from given Parent Array representation

Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation.

We strongly recommend to minimize your browser and try this yourself first.

A Simple Solution to recursively construct by first searching the current root, then recurring for the found indexes (there can be at most two indexes) and making them left and right subtrees of root. This solution takes O(n2) as we have to linearly search for every node.

An Efficient Solution can solve the above problem in O(n) time. The idea is to use extra space. An array created[0..n-1] is used to keep track of created nodes.

createTree(parent[], n)

Create an array of pointers say created[0..n-1]. The value of created[i] is NULL if node for index i is not created, else value is pointer to the created node.

Do following for every index i of given array
createNode(parent, i, created)

createNode(parent[], i, crated[])

If created[i] is not NULL, then node is already created. So return.

Create a new node with value ‘i’.

If parent[i] is -1 (i is root), make created node as root and return.

Check if parent of ‘i’ is created (We can check this by checking if created[parent[i]] is NULL or not.

If parent is not created, recur for parent and create the parent first.

Let the pointer to parent be p. If p->left is NULL, then make the new node as left child. Else make the new node as right child of parent.