All problems

Problem 909

Binary Tree Paths

Easy · 10 pts · Tree, Depth-First Search, Backtracking

Problem

Print every path from the root to a leaf, where a leaf is a node with no children. Write each path as the node values joined by ->, like 1->2->5, one path per line. List the paths in depth-first order, exploring the left child before the right child, which is the order a recursive traversal naturally produces. Build the path string while going down and print it when you reach a leaf.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.

Output

Print each root-to-leaf path on its own line.

Constraints

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

Example input

5
1 2 3 null 5

Example output

1->2->5
1->3

Explanation

In the tree 1 2 3 null 5, the leaves are 5 (under 2) and 3. The paths are 1->2->5 and 1->3, listed with the left subtree first.

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

Previous: Maximum Performance of a Team Next: Second Minimum Node In a Binary Tree