⌘K
Flycodx

Binary Tree Inorder Traversal

Binary Tree Inorder Traversal

EasyTrees100% accepted

Given a binary tree represented as a level-order (BFS) array, perform an inorder traversal and print the node values. In inorder traversal, you visit nodes in the order: Left subtree → Root → Right subtree. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: level-order [1 2 3 4 5 -1 -1] represents a tree where 1 is root, 2 is left child, 3 is right child, 4 and 5 are children of 2. Inorder → "4 2 5 1 3"

Input format — only if your code reads from stdin

Input format (stdin): - First line: integer n (number of values in the level-order array) - Second line: n space-separated integers, where -1 represents a null node Output: the inorder traversal values space-separated on a single line.

Approach

Build the binary tree from the level-order array using a queue. Then run recursive inorder DFS: inorder(node) = inorder(node.left) + [node.val] + inorder(node.right). Skip -1 (null) nodes.

Input

7 1 2 3 4 5 -1 -1

Output

4 2 5 1 3
  • •1 ≤ n ≤ 1000, -100 ≤ node values ≤ 100
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3