← DiffPush

Iterative Preorder Traversal of Binary Tree

Standard Bar Binary Trees · Traversals O(n) · O(n)

The Courier's Return-Address Stack

A night-shift courier audits a delivery franchise's hub-and-branch chart without a guide — no recursive dispatchers allowed after midnight. Armed with a clipboard stack of pending stops, he stamps a hub the moment he reaches it and jots its two branches as pending return addresses. By popping the left branch before the right, his stamp order mirrors the official root-first audit sheet.

Input: The root of a binary tree given as a level-order array where null marks a missing child.

Output: Return an array of node values in preorder, produced without recursion.

Constraints

Examples

Example 1

Input: {"tree":[1,2,3,4,5,null,6]}
Output: [1,2,4,5,3,6]
Identical to recursive preorder: root, left wing, right wing.

Example 2

Input: {"tree":[7]}
Output: [7]
One node, one stamp — the stack empties immediately after.

Solve this in your browser →

Also on LeetCode ↗