Conventional thinking is to take over dfs identify a leaf node, record, delete the leaf node, repeatedly until the tree empty, time complexity is o (n!)
However, we can record from the current node to the leaf node, to complete the subject of the request only once DFS, time complexity is o (n)
public List<List<Integer>> res; public List<List<Integer>> findLeaves(TreeNode root){ res = new ArrayList<>(); if(root == null) return res; dfs(root); return res; } private int dfs(TreeNode root){ if(root == null) return 0; int left = dfs(root.left); int right = dfs(root.right); int depth = Math.max(left, right) + 1; if(depth > res.size()){ res.add(new ArrayList<>(){root.val}); }else{ res.get(depth-1).add(root.val); } return depth; }