Typical DFS problem. Simply get higher height and push_back.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { vector<vector<int>> ret; int go(TreeNode *p) // return max height { if(!p) return 0; int hl = go(p->left); int hr = go(p->right); int h = max(hl, hr) + 1; if(h > ret.size()) ret.push_back({}); ret[h - 1].push_back(p->val); return h; } public: vector<vector<int>> findLeaves(TreeNode* root) { go(root); return ret; } };