All problems

Problem 414

Boundary Traversal of Binary Tree

Medium · 20 pts · Tree, Depth-First Search, Binary Tree

Problem

Print the boundary of a binary tree anticlockwise, starting from the root. The boundary is made of four parts, printed in this order. 1) The root. 2) The left boundary: start at the root's left child and keep moving to the left child (or to the right child when there is no left child), excluding any leaf. 3) All leaves from left to right. 4) The right boundary: start at the root's right child and keep moving to the right child (or to the left child when there is no right child), excluding leaves, printed bottom-up. If the root has no left child, the left boundary is empty, and likewise for the right. A tree that is only a root prints just the root.

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 the boundary values in order, separated by spaces.

Constraints

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

Example input

11
1 2 3 4 5 6 7 null null 8 9

Example output

1 2 4 8 9 6 7 3

Explanation

For 1 / 2 3 / 4 5 6 7 / _ _ 8 9: the root is 1, the left boundary is 2, the leaves are 4 8 9 6 7, and the right boundary is 3. So the boundary is 1 2 4 8 9 6 7 3.

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

Previous: All Nodes at Distance K Next: Diagonal Traversal of Binary Tree