Problem 927
Find Leaves of Binary Tree
Medium · 20 pts · Tree, Depth-First Search
Problem
Repeatedly collect all the leaves of the binary tree, remove them, and continue until the tree is empty. Print each round's leaves on its own line, in left-to-right order. A node is removed in round h + 1, where h is its height (a leaf has height 0), so a single post-order traversal that computes heights can group the nodes by height directly, visiting left subtrees before right ones.
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 one line per round with that round's leaf values in left-to-right order.
Constraints
1 <= number of nodes <= 100; -100 <= value <= 100
Example input
5 1 2 3 4 5
Example output
4 5 3 2 1
Explanation
For 1 2 3 4 5, the first round removes 4, 5 and 3, the second removes 2, and the last removes 1. So the lines are 4 5 3, then 2, then 1.