366. Find Leaves of Binary Tree
阿新 • • 發佈:2021-07-03
Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Example:
Given binary tree
3. Now removing the leaf
Given binary tree
1 / \ 2 3 / \ 4 5Returns
[4, 5, 3], [2], [1]
.
Explanation:
1. Removing the leaves[4, 5, 3]
would result in this tree:
1 / 22. Now removing the leaf
[2]
would result in this tree:
1
[1]
would result in the empty tree:
[]Returns
[4, 5, 3], [2], [1]
.
https://zhuhan0.blogspot.com/2017/05/leetcode-366-find-leaves-of-binary-tree.html
https://www.youtube.com/watch?v=2vwTmHTL1Mk&ab_channel=XavierElon
這題還比較新(對我),解決辦法是計算每個node的height,子節點是0,網上走,root = Math。max(left,right)+ 1。root==null就返回-1.
然後看是否需要加入新的ArrayList,然後把相同height的node加到對應的list中