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
1 / 2 3 / 4 5
Returns [4, 5, 3], [2], [1]
.
Explanation:
1. Removing the leaves [4, 5, 3]
would result in this tree:
1 / 2
2. Now removing the leaf [2]
would result in this tree:
1
3. Now removing the leaf [1]
would result in the empty tree:
[]
Returns [4, 5, 3], [2], [1]
.
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<List<Integer>> findLeaves(TreeNode root) { 12 List<List<Integer> > result = new ArrayList<>(); 13 helper(root, result); 14 return result; 15 } 16 17 private int helper(TreeNode root, List<List<Integer> > result) { 18 if (root == null) return -1; 19 int depth = 1 + Math.max(helper(root.left, result), helper(root.right, result)); 20 if (result.size() < depth + 1) result.add(new ArrayList<Integer>()); 21 result.get(depth).add(root.val); 22 23 return depth; 24 } 25 }