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:
Input: [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
Output: [[4,5,3],[2],[1]]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
help(root,res);
return res;
}
public int help(TreeNode root, List<List<Integer>> res){
if(root==null) return -1;
int level=1+Math.max(help(root.left,res),help(root.right,res));
if(res.size()<level+1) res.add(new ArrayList<>());
res.get(level).add(root.val);
return level;
}
}