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 [].
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.
Input: root = [1,null,2,3] Output: [1,2,3]
2 comes before its left child 3.
0 <= number of comments <= 100000Trees 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.
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).
I'm here to help with #329 Preorder Without Recursion. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.