← Uber bank

Uber · Question 49 · Trees

Preorder & Postorder Traversals

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

Problem

Return preorder (node, left, right) or postorder (left, right, node) traversal of a binary tree.

Approach

Preorder: push root, then right, then left onto the stack. Postorder: reverse a modified preorder.

Time O(n)Space O(h)

How it works

  1. 1Preorder emits node before children via the stack.
  2. 2Postorder emits children first by reversing node-right-left.

Sample input / output

Input:
4
1 x 2 3
Output:
[[1, 2, 3], [3, 2, 1]]

Constraints

0 <= nodes <= 100; -100 <= Node.val <= 100.

Solution — read it, then walk it

Time O(n)Space O(h)Loops 3Branches 9Returns 5source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyes↻ repeat↻ repeatyesnoyesnoyes↻ repeat↻ repeatyesnoyesnoyes↻ repeat↻ repeatSTARTrootif not rootRETURN []res = []stack = [root]while stacknode = stack.pop()res.append(node.val)if node.rightstack.append(node.right)if node.leftstack.append(node.left)RETURN resDEFINEpostorderTraversal(root)if not rootRETURN []res = []stack = [root]while stacknode = stack.pop()res.append(node.val)if node.leftstack.append(node.left)if node.rightstack.append(node.right)RETURN res[::-1]CLASS TreeNodeDEFINE __init__(self,val=0, left=None,right=None)self.val = valself.left = leftself.right = rightDEFINE build_tree(values)if not valuesRETURN Noneroot = TreeNode(values[0])queue = [root]i = 1while queue and i <len(values)node = queue.pop(0)if i < len(values) andvalues[i] is not Nonenode.left =TreeNode(values[i])queue.append(node.left)i += 1if i < len(values) andvalues[i] is not Nonenode.right =TreeNode(values[i])
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/46

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