Binary Trees Traversals
343. Morris Preorder Traversal
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
Input: root = [7, -3, 5, 8, 2, null, 4, null, null, 9, 1]
[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 = []
[]Explanation: The tree has no nodes, so there is nothing to list.
Example 3
Input: root = [1000000000, -1000000000, null, null, 0]
[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.
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.