Binary Tree Preorder Traversal with O(1) Auxiliary Space
Problem statement
Given the root of a binary tree, return its preorder traversal values: root, then left subtree, then right subtree.
Use Morris traversal so the algorithm uses O(1) auxiliary space apart from the returned array. Every temporary pointer must be restored before returning.
Function
preorderTraversal(root: TreeNode) → int[]Examples
Example 1
root = [1,null,2,3]return = [1,2,3]Visit the root, then the right subtree whose left child is three.
Example 2
root = []return = []An empty tree has an empty traversal.
Constraints
- The tree contains between
0and10^5nodes. -10^9 <= Node.val <= 10^9.