Find Leaves of Binary Tree
Medium Trees
root is the root of a binary tree. A node with no children is a leaf; in a tree of one node, that node is a leaf.
Take away all the leaves at once, then all the leaves of the tree that is left, and keep going until nothing is left. A node becomes a leaf once its last child has been taken away, so it goes in a later round.
Return the values taken away in each round, as one list per round, in round order. The values inside one round's list may come in any order.
Example 1
Input: root = [6,2,9,1,4,null,7,null,null,3]
Output: [[1,3,7],[4,9],[2],[6]]
The leaves are 1, 3 and 7. With them gone, 4 and 9 are leaves, then 2, and last 6.
Example 2
Input: root = [4,null,7,null,2]
Output: [[2],[7],[4]]
Example 3
Input: root = [5,5,5]
Output: [[5,5],[5]]
Constraints
1 ≤ number of nodes ≤ 10⁵-10⁹ ≤ node.val ≤ 10⁹- values may repeat
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
More Trees
- Lowest Common Ancestor of a Binary TreeAI round · Medium
- Validate Binary Search TreeAI round · Medium
- Binary Tree Level Order TraversalAI round · Medium
- Binary Tree Vertical Order TraversalMedium
- Inorder Successor in BSTMedium