Workspace Preorder Traversal
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Preorder Traversal visualizer

Visit a complete binary tree in root-left-right order and return its values. The input holds level-order values with no missing nodes.

EXECUTION LAB

Visit a complete binary tree in root-left-right order and return its values. The input holds level-order values with no missing nodes.

Input and constraints
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
stack = [0] * (len(values))
out = [0] * (len(values))
if (len(values) == 0):
return out
top = 1
stack[0] = 0
count = 0
while (top > 0):
top = (top - 1)
node = stack[top]
out[count] = values[node]
count = (count + 1)
right = ((node * 2) + 2)
left = ((node * 2) + 1)
if (right < len(values)):
stack[top] = right
top = (top + 1)
if (left < len(values)):
stack[top] = left
top = (top + 1)
return out

Visualizer

Step 1 of 6
8active4916

Visit the root of the pending subtree

Visit the root of the pending subtree.

Variable watch

node 0count 0

Step explanation

Visit the root of the pending subtree.

comparisons 2reads 1writes 1swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(n) allocated stack and output space

Worked explanation

When two rooms branch off, put the later room on the to-do pile before the room to visit now.

Guided solution

A stack drives traversal. Push the right child first so the left child is popped first.

O(n) time · O(n) allocated stack and output auxiliary space

Examples

Worked example · {"values":[8,4,9,1,6],"target":0} ⇒ [8,4,1,6,9]

Edge case 1 · {"values":[],"target":0} ⇒ []

Edge case 2 · {"values":[7],"target":0} ⇒ [7]

Progressive hints

Hint 1When two rooms branch off, put the later room on the to-do pile before the room to visit now.
Hint 2A stack drives traversal. Push the right child first so the left child is popped first.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Pushing the left child first reverses the intended visit order.

Interview follow-up

How could a null marker represent sparse trees?

Continue learning

Practice related DSA questions in the same topic.