Skip to the code
cf.
+10 XP

#329 Preorder Without Recursion

easy

A forum stores each comment thread as a binary tree: a comment's left is its first reply, and its right is the next comment at the same level. Reading the thread top to bottom is a preorder walk: a comment, then everything under its left, then everything under its right.

Threads can be tens of thousands of comments deep, which would overflow the call stack. Write readingOrder(root) that returns the comment ids in preorder without using recursion. An empty thread returns [].

Example 1

Input: root = [1,2,5,3,4]
Output: [1,2,3,4,5]

Preorder visits 1, then 1's left side 2, 3, 4, then its right side 5.

Example 2

Input: root = [1,null,2,3]
Output: [1,2,3]

2 comes before its left child 3.

Constraints

  • 0 <= number of comments <= 100000
  • The tree may be a single long chain.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).