oneby7

Binary Trees Traversals

342. Morris Inorder Traversal

Hard

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

Inorder lists a node's whole left subtree first, then the node, then its whole right subtree. Each subtree is listed in inorder too. 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

916348-2

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

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

Explanation: The left subtree of 4 comes first. Its top node 9 has no left child, so 9 is listed first, then its right subtree in inorder: 1, 6, 3. Then comes 4, and then the right subtree: 8, then −2.

Example 2

Input: root = []

Output: []

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

Example 3

−10⁹710⁹7

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

Output: [-1000000000,7,1000000000,7]

Explanation: The lower 7 comes between its two children, and the root 7 comes last because it has no right subtree. Values can repeat, and each node is listed once.

Check your understanding

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

root = [10, -3, 7, 5, 0, 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.