Preorder Traversal
Visit a complete binary tree in root-left-right order and return its values. The input holds level-order values with no missing nodes.
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 outVisualizer
Step 1 of 6Visit the root of the pending subtree
Visit the root of the pending subtree.
Variable watch
Step explanation
Visit the root of the pending subtree.
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 1
When two rooms branch off, put the later room on the to-do pile before the room to visit now.Hint 2
A stack drives traversal. Push the right child first so the left child is popped first.Hint 3
Step 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?