Binary Trees Traversals
338. Binary Tree Preorder Traversal
You are given root, the root node of a binary tree. Return the values of all its nodes in preorder.
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 [].
Leave the tree as you found it. When your function returns, every node must still have its own value and its own two children.
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 = [5, 2, 9, 7, 4, null, 1, null, null, 3]
[5,2,7,4,3,9,1]Explanation: The root 5 comes first. Then comes its left subtree in preorder: 2, its left child 7, and its right child 4 with 4's child 3. The right subtree comes last: 9, then 1.
Example 2
Input: root = []
[]Explanation: The tree has no nodes, so there is nothing to list.
Example 3
Input: root = [-4, null, 1000000000, -1000000000]
[-4,1000000000,-1000000000]Explanation: −4 has no left subtree, so its right child 1000000000 comes next. Then comes that child's left child, −1000000000.
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.