Data Structures19 sections · 729 units
Open in Course

Binary Tree from Array

Level-order construction

Many problems give trees in array format: [3,9,20,null,null,15,7][3, 9, 20, null, null, 15, 7].

You're looking at level-order representation:

  • Index 0 is root
  • For node at index ii: left child at 2i+12i+1, right child at 2i+22i+2
  • null indicates missing node
function arrayToTree(arr):
    if arr is empty:
        return null
    root = TreeNode(arr[0])
    queue = [root]
    i = 1
    while queue and i < arr.length:
        node = queue.dequeue()
        if arr[i] != null:
            node.left = TreeNode(arr[i])
            queue.append(node.left)
        i += 1
        if i < arr.length and arr[i] != null:
            node.right = TreeNode(arr[i])
            queue.append(node.right)
        i += 1
    return root

This BFS approach builds the tree level by level.