oneby7

Binary Trees Traversals

338. Binary Tree Preorder Traversal

Easy

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

7234591

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

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

Output: []

Explanation: The tree has no nodes, so there is nothing to list.

Example 3

-4−10⁹10⁹

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

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

root = [6, 8, 2, null, 5, 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.