All problems

Problem 155

Binary Tree Right Side View

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

Problem

Imagine standing to the right of a binary tree and looking at it. On each level you can see only the rightmost node. Print the values you can see, from the top level to the bottom. Note that the visible node of a level is not always in the right subtree of the root: if the right side is shorter, nodes from the left subtree show through on the deeper levels. A level-order traversal that takes the last node of each level handles this.

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 visible values, space-separated.

Constraints

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

Example input

7
1 2 3 null 5 null 4

Example output

1 3 4

Explanation

Level 1 is 1, level 2 is 2 3 and level 3 is 5 4. The last node of each level is 1, 3 and 4, so the right side view is 1 3 4.

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

Previous: Kth Smallest Element in a BST Next: Binary Tree Zigzag Level Order