oneby7

Binary Trees Traversals

339. Binary Tree Inorder Traversal

Easy

You are given root, the root node of a binary tree. Return the values of its nodes in inorder.

Inorder lists a tree in three parts: first its left subtree in inorder, then the root, then its right subtree in inorder. A missing subtree adds nothing. So every node comes after all the nodes below its left child and before all the nodes below its right child. An empty tree gives [].

Leave the tree as you found it: when your function returns, every node must hold its original value and 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

347815

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

Output: [3,4,7,8,1,5]

Explanation: The left subtree of 8 holds 3, 7 and 4. 3 has no left child, so it comes first, and then its right subtree gives 4 before its parent 7. Then comes 8, and then its right subtree, where 1 comes before its parent 5.

Example 2

Input: root = []

Output: []

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

Example 3

010⁹−10⁹

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

Output: [0,1000000000,-1000000000]

Explanation: Each node has only a left child, so the deepest node comes first and the root comes last.

Check your understanding

Work out the answer for this input before you write any code.

root = [1, 2, 3, 4, 5]

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.