My C++ Approach, Tell me how to optimize


#1
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
void DFS(TreeNode*root,int level,vector<vector<int>>&ans)
{
    if(!root)
        return;
    if(ans.size() == level)
        ans.push_back(vector<int>());
    ans[level].push_back(root->val);
    DFS(root->left,level+1,ans);
    DFS(root->right,level+1,ans);
}
vector<int> Solution::solve(TreeNode* A) 
{
    vector<vector<int>> ans;
    DFS(A,0,ans);
    vector<int> result;
    for(int i=ans.size()-1;i>=0;i--)
    {
        int m = ans[i].size();
        for(int j=0;j<m;j++)
            result.push_back(ans[i][j]);
    }
    return result;
}