oneby7

Binary Trees Traversals

341. Preorder, Inorder and Postorder in One Pass

Medium

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

69314-25

Input: root = [4, 9, -2, 6, 1, null, 5, null, null, 3]

Output: [[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 = []

Output: [[],[],[]]

Explanation: The tree has no nodes, so all three lists are empty.

Example 3

10⁹0−10⁹

Input: root = [-1000000000, 1000000000, null, null, 0]

Output: [[-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.

root = [2, 7, 5, null, null, 1, 3]

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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.