My concise recursive answer[C++], easy to understand.


  • 1
    W
    class Solution {
    public:
        int find_func(TreeNode* node, vector<vector<int>>& ret) {
            if (!node) return -1;
            int left = find_func(node->left, ret);
            int right = find_func(node->right, ret);
            if (ret.size() <= max(left,right) + 1) ret.push_back(vector<int>());
            ret[ max(left,right) + 1].push_back(node->val);
            return max(left,right) + 1;
        }
        vector<vector<int>> findLeaves(TreeNode* root) {
            vector<vector<int>> ret;
            find_func(root,ret);
            return ret;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.