Straight-forward c++ solution by reference with dfs


  • 2
    Y
    class Solution {
    void dfs(vector<int> &aLevel, TreeNode *&root) {
        if(!root->left && !root->right) {
            aLevel.push_back(root->val);
            // delete root;
            root = NULL;
        }
        else {
            if(root->left)
                dfs(aLevel,root->left);
            if(root->right)
                dfs(aLevel,root->right);
        }
    }
    public:
    vector<vector<int>> findLeaves(TreeNode* root) {
        vector<vector<int>> res;
        
        while(root) {
            vector<int> aLevel;
            dfs(aLevel,root);
            res.push_back(aLevel);
        }
        
        return res;
    }
    };

Log in to reply
 

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