← Uber bank

Uber · Question 52 · Trees

Construct Binary Tree from Preorder and Inorder

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

Problem

Given preorder and inorder traversal of a binary tree, construct the original tree.

Approach

 First node in preorder is root.  Use hashmap to find root index in inorder.  Recursively build left and right subtrees using sliced lists or indices.

Time O(n)Space O(n)

How it works

  1. 1The preorder head is the subtree root.
  2. 2Its inorder index splits left/right ranges.
  3. 3Recurse with index ranges (O(1) lookup via hashmap).

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; unique values; valid traversals.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 2Branches 5Returns 5source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesno↻ repeat↻ repeatyesnoSTARTpreorder, inorderinorder_index = {val: i fori, val inenumerate(inorder)}DEFINE helper(pre_left,pre_right, in_left,in_right)if pre_left >pre_rightRETURN Noneroot_val =preorder[pre_left]root = TreeNode(root_val)index =inorder_index[root_val]left_size = index - in_leftroot.left = helper(pre_left+ 1, pre_left + left_size,in_left, index - 1)root.right =helper(pre_left + left_size+ 1, pre_right, index + 1…RETURN rootRETURN helper(0,len(preorder) - 1, 0,len(inorder) - 1)CLASS 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/45

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