Construct Binary Tree from Parent Array

Last Updated : 15 Sep, 2026

Given an array parent[] where each index represents a node and parent[i] gives the parent’s index, with -1 indicating the root. Your task is to construct the binary tree in standard linked-node form (each node having left and right pointers) based on this parent–child relationship and return the root node.

Note: If two elements have the same parent, the one that appears first in the array will be the left child and the other is the right child.

Examples:

Input: parent[] = [-1, 0, 0, 1, 1, 3, 5]
Output: [0, 1, 2, 3, 4, N, N, 5, N, N, N, 6]
Explanation: The tree generated will have a structure like:

1292

Input: parent[] = [2, 0, -1]
Output: [2, 0, N, 1]
Explanation: The tree generated will have a structure like:

1293
Try It Yourself
redirect icon

[Naive Approach] Brute Force Approach - O(n^2) Time and O(n) Space

The idea is to first create all the tree nodes and then, for every node, search the parent[] array to find its parent node.

Once the parent is found, we attach the current node as the left child if the left pointer is empty; otherwise, we attach it as the right child.

  • Create one Node for every index and store them in an array.
  • Traverse every node i from 0 to n - 1.
  • If parent[i] == -1, mark node i as the root.
  • Otherwise, search for the node whose index is parent[i].
  • Attach node i to the parent's left child if it is empty; otherwise attach it to the right.
  • Return the root node.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int x)
    {
        data = x;
        left = right = nullptr;
    }
};

Node *createTree(vector<int> &parent)
{
    int n = parent.size();

    // Create all nodes.
    vector<Node *> nodes(n);

    for (int i = 0; i < n; i++)
        nodes[i] = new Node(i);

    Node *root = nullptr;

    // Process every node.
    for (int i = 0; i < n; i++)
    {
        // If parent is -1, this node is the root.
        if (parent[i] == -1)
        {
            root = nodes[i];
            continue;
        }

        // Search for the parent node.
        Node *p = nullptr;

        for (int j = 0; j < n; j++)
        {
            if (j == parent[i])
            {
                p = nodes[j];
                break;
            }
        }

        // Attach as the left child if empty.
        if (p->left == nullptr)
            p->left = nodes[i];

        // Otherwise, attach as the right child.
        else
            p->right = nodes[i];
    }

    return root;
}

// Function to print level order traversal.
void levelOrder(Node *root)
{
    if (root == nullptr)
        return;

    queue<Node *> q;
    q.push(root);

    while (!q.empty())
    {
        Node *curr = q.front();
        q.pop();

        cout << curr->data << " ";

        if (curr->left != nullptr)
            q.push(curr->left);

        if (curr->right != nullptr)
            q.push(curr->right);
    }
}

int main()
{
    vector<int> parent = {-1, 0, 0, 1, 1, 3, 5};
    Node *root = createTree(parent);

    levelOrder(root);

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node left;
    Node right;

    Node(int x)
    {
        data = x;
        left = right = null;
    }
}

class GFG {
    static Node createTree(int[] parent)
    {
        int n = parent.length;
        Node[] nodes = new Node[n];

        for (int i = 0; i < n; i++)
            nodes[i] = new Node(i);

        Node root = null;

        // Process every node
        for (int i = 0; i < n; i++) {
            
            // If this node is the root.
            if (parent[i] == -1) {
                root = nodes[i];
                continue;
            }

            // Search for the parent node.
            Node p = null;

            for (int j = 0; j < n; j++) {
                if (j == parent[i]) {
                    p = nodes[j];
                    break;
                }
            }

            // Attach as the left child if empty.
            if (p.left == null)
                p.left = nodes[i];

            // Otherwise, attach as the right child.
            else
                p.right = nodes[i];
        }

        return root;
    }

    // Function to print level order traversal.
    static void levelOrder(Node root)
    {
        if (root == null)
            return;

        Queue<Node> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            Node curr = q.poll();

            System.out.print(curr.data + " ");

            if (curr.left != null)
                q.add(curr.left);

            if (curr.right != null)
                q.add(curr.right);
        }
    }

    public static void main(String[] args)
    {
        int[] parent = { -1, 0, 0, 1, 1, 3, 5 };
        Node root = createTree(parent);

        levelOrder(root);
    }
}
Python
from collections import deque

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


def createTree(parent):
    n = len(parent)

    # Create all nodes.
    nodes = [None] * n

    for i in range(n):
        nodes[i] = Node(i)

    root = None

    # Process every node.
    for i in range(n):

        # If this node is the root.
        if parent[i] == -1:
            root = nodes[i]
            continue

        # Search for the parent node.
        p = None

        for j in range(n):
            if j == parent[i]:
                p = nodes[j]
                break

        # Attach as the left child if empty.
        if p.left is None:
            p.left = nodes[i]

        # Otherwise, attach as the right child.
        else:
            p.right = nodes[i]

    return root


# Function to print level order traversal.
def levelOrder(root):
    if root is None:
        return

    q = deque()
    q.append(root)

    while q:
        curr = q.popleft()

        print(curr.data, end=" ")

        if curr.left is not None:
            q.append(curr.left)

        if curr.right is not None:
            q.append(curr.right)


# Driver Code
if __name__ == "__main__":
    parent = [-1, 0, 0, 1, 1, 3, 5]
    root = createTree(parent)

    levelOrder(root)
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int x)
    {
        data = x;
        left = right = null;
    }
}

class GFG {
    static Node createTree(int[] parent)
    {
        int n = parent.Length;

        // Create all nodes.
        Node[] nodes = new Node[n];

        for (int i = 0; i < n; i++)
            nodes[i] = new Node(i);

        Node root = null;

        // Process every node.
        for (int i = 0; i < n; i++) {
            // If this node is the root.
            if (parent[i] == -1) {
                root = nodes[i];
                continue;
            }

            // Search for the parent node.
            Node p = null;

            for (int j = 0; j < n; j++) {
                if (j == parent[i]) {
                    p = nodes[j];
                    break;
                }
            }

            // Attach as the left child if empty.
            if (p.left == null)
                p.left = nodes[i];

            // Otherwise, attach as the right child.
            else
                p.right = nodes[i];
        }

        return root;
    }

    // Function to print level order traversal.
    static void levelOrder(Node root)
    {
        if (root == null)
            return;

        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {
            Node curr = q.Dequeue();

            Console.Write(curr.data + " ");

            if (curr.left != null)
                q.Enqueue(curr.left);

            if (curr.right != null)
                q.Enqueue(curr.right);
        }
    }

    public static void Main()
    {
        int[] parent = { -1, 0, 0, 1, 1, 3, 5 };
        Node root = createTree(parent);

        levelOrder(root);
    }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function createTree(parent)
{
    const n = parent.length;

    // Create all nodes.
    const nodes = new Array(n);

    for (let i = 0; i < n; i++)
        nodes[i] = new Node(i);

    let root = null;

    // Process every node.
    for (let i = 0; i < n; i++) {

        // If this node is the root.
        if (parent[i] === -1) {
            root = nodes[i];
            continue;
        }

        // Search for the parent node.
        let p = null;

        for (let j = 0; j < n; j++) {
            if (j === parent[i]) {
                p = nodes[j];
                break;
            }
        }

        // Attach as the left child if empty.
        if (p.left === null)
            p.left = nodes[i];

        // Otherwise, attach as the right child.
        else
            p.right = nodes[i];
    }

    return root;
}

// Function to print level order traversal.
function levelOrder(root)
{
    if (root === null)
        return;

    const q = [];
    let idx = 0;

    q.push(root);

    let res = "";

    while (idx < q.length) {
        const curr = q[idx++];

        res += curr.data + " ";

        if (curr.left !== null)
            q.push(curr.left);

        if (curr.right !== null)
            q.push(curr.right);
    }

    console.log(res.trim());
}

// Driver Code
const parent = [ -1, 0, 0, 1, 1, 3, 5 ];
const root = createTree(parent);

levelOrder(root);

Output
0 1 2 3 4 5 6 

[Expected Approach] Create All Nodes First and Link Them - O(n) Time and O(n) Space

The idea is to first create one node for every index and store all node pointers in an array. Since the node index directly corresponds to its position in parent[], we can directly access any parent node using nodes[parent[i]].

Then, while traversing the parent array from left to right, attach each node to its parent's left child if it is empty; otherwise, attach it to the right. This also naturally preserves the required left-to-right child order.

  • Create an array nodes[] and create one node for every index.
  • Traverse parent[] from left to right.
  • If parent[i] == -1, make nodes[i] the root.
  • Otherwise, directly access the parent using nodes[parent[i]].
  • Attach the current node as the left child if it is empty; otherwise attach it as the right child.
  • Return the root node.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int x)
    {
        data = x;
        left = right = nullptr;
    }
};

Node *createTree(vector<int> &parent)
{
    int n = parent.size();

    // Create all nodes.
    vector<Node *> nodes(n);

    for (int i = 0; i < n; i++)
        nodes[i] = new Node(i);

    Node *root = nullptr;

    // Process every node.
    for (int i = 0; i < n; i++)
    {
        // If this node is the root.
        if (parent[i] == -1)
        {
            root = nodes[i];
            continue;
        }

        // Get the parent node directly.
        Node *p = nodes[parent[i]];

        // Attach as the left child if empty.
        if (p->left == nullptr)
            p->left = nodes[i];

        // Otherwise, attach as the right child.
        else
            p->right = nodes[i];
    }

    return root;
}

// Function to print level order traversal.
void levelOrder(Node *root)
{
    if (root == nullptr)
        return;

    queue<Node *> q;
    q.push(root);

    while (!q.empty())
    {
        Node *curr = q.front();
        q.pop();

        cout << curr->data << " ";

        if (curr->left != nullptr)
            q.push(curr->left);

        if (curr->right != nullptr)
            q.push(curr->right);
    }
}

int main()
{
    vector<int> parent = {-1, 0, 0, 1, 1, 3, 5};
    Node *root = createTree(parent);

    levelOrder(root);

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node left;
    Node right;

    Node(int x)
    {
        data = x;
        left = right = null;
    }
}

class GFG {
    static Node createTree(int[] parent)
    {
        int n = parent.length;

        // Create all nodes.
        Node[] nodes = new Node[n];

        for (int i = 0; i < n; i++)
            nodes[i] = new Node(i);

        Node root = null;

        // Process every node.
        for (int i = 0; i < n; i++) {
            // If this node is the root.
            if (parent[i] == -1) {
                root = nodes[i];
                continue;
            }

            // Get the parent node directly.
            Node p = nodes[parent[i]];

            // Attach as the left child if empty.
            if (p.left == null)
                p.left = nodes[i];

            // Otherwise, attach as the right child.
            else
                p.right = nodes[i];
        }

        return root;
    }

    // Function to print level order traversal.
    static void levelOrder(Node root)
    {
        if (root == null)
            return;

        Queue<Node> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            Node curr = q.poll();

            System.out.print(curr.data + " ");

            if (curr.left != null)
                q.add(curr.left);

            if (curr.right != null)
                q.add(curr.right);
        }
    }

    public static void main(String[] args)
    {
        int[] parent = { -1, 0, 0, 1, 1, 3, 5 };
        Node root = createTree(parent);

        levelOrder(root);
    }
}
Python
from collections import deque


class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


def createTree(parent):
    n = len(parent)

    # Create all nodes.
    nodes = [None] * n

    for i in range(n):
        nodes[i] = Node(i)

    root = None

    # Process every node.
    for i in range(n):

        # If this node is the root.
        if parent[i] == -1:
            root = nodes[i]
            continue

        # Get the parent node directly.
        p = nodes[parent[i]]

        # Attach as the left child if empty.
        if p.left is None:
            p.left = nodes[i]

        # Otherwise, attach as the right child.
        else:
            p.right = nodes[i]

    return root


# Function to print level order traversal.
def levelOrder(root):
    if root is None:
        return

    q = deque()
    q.append(root)

    while q:
        curr = q.popleft()

        print(curr.data, end=" ")

        if curr.left is not None:
            q.append(curr.left)

        if curr.right is not None:
            q.append(curr.right)


# Driver Code
if __name__ == "__main__":
    parent = [-1, 0, 0, 1, 1, 3, 5]
    root = createTree(parent)

    levelOrder(root)
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int x)
    {
        data = x;
        left = right = null;
    }
}

class GFG {
    static Node createTree(int[] parent)
    {
        int n = parent.Length;

        // Create all nodes.
        Node[] nodes = new Node[n];

        for (int i = 0; i < n; i++)
            nodes[i] = new Node(i);

        Node root = null;

        // Process every node.
        for (int i = 0; i < n; i++) {
            // If this node is the root.
            if (parent[i] == -1) {
                root = nodes[i];
                continue;
            }

            // Get the parent node directly.
            Node p = nodes[parent[i]];

            // Attach as the left child if empty.
            if (p.left == null)
                p.left = nodes[i];

            // Otherwise, attach as the right child.
            else
                p.right = nodes[i];
        }

        return root;
    }

    // Function to print level order traversal.
    static void levelOrder(Node root)
    {
        if (root == null)
            return;

        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {
            Node curr = q.Dequeue();

            Console.Write(curr.data + " ");

            if (curr.left != null)
                q.Enqueue(curr.left);

            if (curr.right != null)
                q.Enqueue(curr.right);
        }
    }

    public static void Main()
    {
        int[] parent = { -1, 0, 0, 1, 1, 3, 5 };
        Node root = createTree(parent);

        levelOrder(root);
    }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function createTree(parent)
{
    const n = parent.length;

    // Create all nodes.
    const nodes = new Array(n);

    for (let i = 0; i < n; i++)
        nodes[i] = new Node(i);

    let root = null;

    // Process every node.
    for (let i = 0; i < n; i++) {

        // If this node is the root.
        if (parent[i] === -1) {
            root = nodes[i];
            continue;
        }

        // Get the parent node directly.
        const p = nodes[parent[i]];

        // Attach as the left child if empty.
        if (p.left === null)
            p.left = nodes[i];

        // Otherwise, attach as the right child.
        else
            p.right = nodes[i];
    }

    return root;
}

// Function to print level order traversal.
function levelOrder(root)
{
    if (root === null)
        return;

    const q = [];
    let idx = 0;

    q.push(root);

    let res = "";

    while (idx < q.length) {
        const curr = q[idx++];

        res += curr.data + " ";

        if (curr.left !== null)
            q.push(curr.left);

        if (curr.right !== null)
            q.push(curr.right);
    }

    console.log(res.trim());
}

// Driver Code
const parent = [ -1, 0, 0, 1, 1, 3, 5 ];
const root = createTree(parent);

levelOrder(root);

Output
0 1 2 3 4 5 6 

Similar Problem: Find Height of Binary Tree represented by Parent array

Comment