All problems

Problem 142

Binary Tree Inorder Traversal

Easy · 10 pts · Tree, Stack, Binary Tree

Problem

You are given a binary tree. Print its inorder traversal: for every node, first visit its whole left subtree, then the node itself, then its whole right subtree. A recursive function is the most natural solution. An iterative version uses a stack: go as far left as possible pushing nodes, then pop a node, visit it, and continue with its right child. For a binary search tree, inorder visits the values in sorted order.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child (the same format LeetCode uses).

Output

Print the values in inorder, space-separated.

Constraints

1 <= number of nodes <= 10000; -100 <= value <= 100

Example input

4
1 null 2 3

Example output

1 3 2

Explanation

The root 1 has no left child and a right child 2, and 2 has a left child 3. Inorder visits 1 (its left subtree is empty), then the subtree of 2, where 3 comes before 2. The order is 1 3 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Maximum Depth of Binary Tree Next: Binary Tree Preorder Traversal