337. Right View of a Tree
Print the last node of each row, top to bottom: what you would see standing to the right of the tree.
4
/ \
2 6 right view is 4 6 7
/ \ / \
1 3 5 7
The mirror of the previous problem, and it needs one change of approach. The left view could take the FIRST node at each depth and stop thinking about that row. The right view cannot know a node is last until the row is finished, so keep overwriting the answer for each depth and print what remains.
Constraints - `1 ≤ n ≤ 100000` - `-1000000000 ≤ value ≤ 1000000000` - The input always forms a valid tree rooted at node 1.
Input
The first line contains an integer n, the number of nodes.
The second line contains n values, where node i holds the ith value.
Each of the next n lines contains two integers, the left and right child of
node i, using 0 for no child. Node 1 is the root.
Output
Print the last value of each row, top to bottom, separated by single spaces.