oneby7

Binary Trees Traversals

343. Morris Preorder Traversal

Hard

You are given root, the root node of a binary tree. Return the values of all its nodes in preorder. Use only O(1) extra memory besides the list you return: no stack, no queue and no recursion.

Preorder lists a node before the nodes below it. It starts with the root, then lists the root's whole left subtree in preorder, and then its whole right subtree in preorder. A missing subtree adds nothing, and an empty tree gives [].

When your function returns, the tree must be exactly as you found it: every node with its own value and its own two children. If a node's value or one of its children is different, the judge shows what changed instead of your answer.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

8-3921754

Input: root = [7, -3, 5, 8, 2, null, 4, null, null, 9, 1]

Output: [7,-3,8,2,9,1,5,4]

Explanation: The root 7 comes first. Then comes its left subtree in preorder: −3, its left child 8, and its right child 2 followed by 2's children 9 and 1. The right subtree comes last: 5, then 4.

Example 2

Input: root = []

Output: []

Explanation: The tree has no nodes, so there is nothing to list.

Example 3

−10⁹010⁹

Input: root = [1000000000, -1000000000, null, null, 0]

Output: [1000000000,-1000000000,0]

Explanation: The root has only a left child, −1000000000, and that child has only a right child, 0. Each node comes before the nodes below it.

Check your understanding

Work out the answer for this input before you write any code.

root = [5, 1, 8, 9, 3, null, 2]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.