910. Morris Preorder Traversal (O(1) Space)

MediumTreesBinary TreeMorris TraversalThreaded Tree

Given the root of a binary tree, return its preorder traversal using Morris traversal — O(1) extra space, no recursion or explicit stack. Record each node when the thread is first created. Return the values as an array. The tree is given as a level-order array.

Input: A level-order array of the tree.

Output: Array — node values in preorder.

Examples

Example 1
Input: [1,2,3,4,5,null,7]
Output: [1,2,4,5,3,7]
Explanation: Preorder via threaded links.
Example 2
Input: [1]
Output: [1]
Explanation: Single node.
Example 3
Input: []
Output: []
Explanation: Empty tree.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →