Many problems give trees in array format: .
You're looking at level-order representation:
- Index 0 is root
- For node at index : left child at , right child at
nullindicates 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.