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
def arrayToTree(arr):
if not arr:
return null
root = TreeNode(arr[0])
queue = [root]
i = 1
while queue and i < len(arr):
node = queue.pop(0)
if arr[i] is not None:
node.left = TreeNode(arr[i])
queue.append(node.left)
i += 1
if i < len(arr) and arr[i] is not None:
node.right = TreeNode(arr[i])
queue.append(node.right)
i += 1
return root
This BFS approach builds the tree level by level.