Binary Tree Inorder Traversal - aloalgo

Binary Tree Inorder Traversal

Easy

You are given the root of a binary tree, return the inorder traversal of its nodes' values.

In an inorder traversal, we recursively follow these steps:

  1. Traverse the left subtree.
  2. Visit the root node.
  3. Traverse the right subtree.

Example 1

Input
123
Output
[1, 3, 2]
Explanation:

Starting at the root (1), we go to its right child (2) since the left is null. From node 2, we go to its left child (3). Node 3 has no children, so we add 3 to the list. Then we go back to node 2 and add 2. Finally, we go back to the root and add 1. The result is [1, 3, 2], which is incorrect. Let's re-evaluate.

Correct Inorder Traversal:

  1. Start at root (1). Does it have a left child? No.
  2. Visit the root node (1). Result: [1].
  3. Traverse the right subtree, rooted at 2.
  4. At node 2, does it have a left child? Yes, 3.
  5. At node 3, does it have a left child? No.
  6. Visit node 3. Result: [1, 3].
  7. At node 3, does it have a right child? No.
  8. Return to node 2. Visit node 2. Result: [1, 3, 2].
  9. At node 2, does it have a right child? No.
  10. Traversal is complete. Final result: [1, 3, 2].

Example 2

Input
None
Output
[]
Explanation:

The tree is empty, so the traversal results in an empty list.

Example 3

Input
4213769
Output
[1, 2, 3, 4, 6, 7, 9]
Explanation:

Following the left-root-right pattern recursively results in the nodes being visited in their natural sorted order for a Binary Search Tree, which this example happens to be.

Loading...
Input
123
Output
[1, 3, 2]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!