Time:O(n) Space:O(h) C++ class Solution { public: vector<vector<int>> findLeaves(TreeNode* root) { vector<vector<int>> ans; depth(root, ans); return ans; } private: // depth of root (0-indexed) int depth(TreeNode* root, vector<vector<int>>& ans) { if (!root) return -1; const int l = depth(root->left, ans); const int r = depth(root->right, ans); const int h = 1 + max(l, r); if (ans.size() == h) // meet leaf ans.push_back({}); ans[h].push_back(root->val); return h; } }; JAVA class Solution { public List<List<Integer>> findLeaves(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); depth(root, ans); return ans; } // depth of root (0-indexed) private int depth(TreeNode root, List<List<Integer>> ans) { if (root == null) return -1; final int l = depth(root.left, ans); final int r = depth(root.right, ans); final int h = 1 + Math.max(l, r); if (ans.size() == h) // meet leaf ans.add(new ArrayList<>()); ans.get(h).add(root.val); return h; } }