Clean c++ O(n) solution


  • 1

    Traverse in post-order, and update result in each level

    vector<vector<int>> findLeaves(TreeNode* root) {
        vector<vector<int>> result;
        findLeaves(root, result);
        return result;
    }
    
    int findLeaves(TreeNode *root, vector<vector<int>> &result) {
        if (root == NULL)
            return 0;
        int left = findLeaves(root->left, result);
        int right = findLeaves(root->right, result);
        int self = max(left, right);
        while (result.size() <= self)
            result.push_back(vector<int>());
        result[self].push_back(root->val);
        return self + 1;
    }
    

Log in to reply
 

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