← Google bank

Google · Question 59 · Trees

Construct Binary Tree from Preorder and Inorder Traversal

TreesPythoncode⏱ O(n²)💾 O(n)
Product-based

Problem

Build a binary tree from preorder and inorder traversal arrays.

Approach

Use the preorder root and inorder partition to build the tree recursively.

Time O(n²)Space O(n)

How it works

  1. 1The first preorder element is the root.
  2. 2Find the root in inorder to split left/right subtrees.
  3. 3Recursively build the left and right subtrees.

Sample input / output

Input:
5
3 9 20 15 7
5
9 3 15 20 7
Output:
[3, 9, 20, None, None, 15, 7]

Constraints

1 <= nodes <= 3000; values unique; valid traversals guaranteed.

Solution — read it, then walk it

Time O(n²)Space O(n)Loops 2Branches 5Returns 4source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesno↻ repeat↻ repeatyesnoSTARTpreorder, inorderif not preorder or notinorderRETURN Noneroot_val = preorder[0]root = TreeNode(root_val)mid =inorder.index(root_val)root.left =buildTree(preorder[1:mid +1], inorder[:mid])root.right =buildTree(preorder[mid +1:], inorder[mid + 1:])RETURN rootCLASS TreeNodeDEFINE __init__(self,val=0, left=None,right=None)self.val = valself.left = leftself.right = rightDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))preorder = [int(next(it))for _ in range(n)]m = int(next(it))inorder = [int(next(it))for _ in range(m)]root = buildTree(preorder,inorder)DEFINElevel_with_none(root)if not rootRETURN []out, queue = [], [root]while queuenode = queue.pop(0)if nodeout.append(node.val)queue += [node.left,node.right]ELSEout.append(None)while out and out[-1]is Noneout.pop()RETURN outprint(level_with_none(root))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/41

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits