Given the root of a binary tree, collect a tree's nodes as if you were doing this:
Collect all the leaf nodes.
Remove all the leaf nodes.
Repeat until the tree is empty.
Example 1:
Input: root = [1,2,3,4,5]
Output: [[4,5,3],[2],[1]]
Explanation:
[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.
Example 2:
Input: root = [1]
Output: [[1]]
解答
方法一
一輪一輪的把所有葉子節點挑出來後,再依序加入結果的矩陣
Runtime: 99 ms, faster than 21.85% of JavaScript online submissions for Find Leaves of Binary Tree.
Memory Usage: 42.4 MB, less than 56.31% of JavaScript online submissions for Find Leaves of Binary Tree.
方法二
計算每個節點的高度,依序存到結果矩陣 [ 高度為0的節點, 高度為1的節點, ......]
Runtime: 90 ms, faster than 35.45% of JavaScript online submissions for Find Leaves of Binary Tree.
Memory Usage: 42.2 MB, less than 67.03% of JavaScript online submissions for Find Leaves of Binary Tree.