Binary Trees Traversals
341. Preorder, Inorder and Postorder in One Pass
You are given root, the root node of a binary tree. Return three lists: the values of its nodes in
preorder, in inorder and in postorder, in that order.
Preorder lists a node, then its left subtree in preorder, then its right subtree in preorder. Inorder lists
the left subtree first, then the node, then the right subtree. Postorder lists the left subtree, then the
right subtree, and the node last. A missing subtree adds nothing, so 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 = [4, 9, -2, 6, 1, null, 5, null, null, 3]
[[4,9,6,1,3,-2,5],[6,9,3,1,4,-2,5],[6,3,1,9,5,-2,4]]Explanation: Preorder writes 4 first, then the left subtree 9, 6, 1, 3, then the right subtree −2, 5. Inorder writes 4 between its two subtrees. Postorder writes 4 last, after 6, 3, 1, 9 and 5, −2.
Example 2
Input: root = []
[[],[],[]]Explanation: The tree has no nodes, so all three lists are empty.
Example 3
Input: root = [-1000000000, 1000000000, null, null, 0]
[[-1000000000,1000000000,0],
[1000000000,0,-1000000000],
[0,1000000000,-1000000000]]Explanation: 0 is the right child of 1000000000. So inorder writes 1000000000 before 0, and postorder writes it after 0.
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.