Find Leaves of Binary Tree
Last updated
Last updated
1 []class Solution {
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
helper(root, res);
return res;
}
private int helper(TreeNode root, List<List<Integer>> res) {
if (root == null) {
return -1;
}
int level = 1 + Math.max(helper(root.left, res),
helper(root.right, res));
if (res.size() == level) {
res.add(new ArrayList<Integer>());
}
res.get(level).add(root.val);
root.left = root.right = null;
return level;
}
}