[Accepted] My recursive solution in C++


  • 0
    L
    class Solution {
    public:
        vector<vector<int> > levelOrder(TreeNode *root) {
           vector<vector<int> > ans; 
    	   dfsLevelOrder(root, 0, ans);
    	   return ans;
        }
    private:
    	void dfsLevelOrder(const TreeNode *root, int level, vector<vector<int> > & ans) const {
    		if (root == nullptr)
    			return;
    		while (ans.size() <= level)
    			ans.push_back(vector<int>());
    		ans[level].push_back(root->val);
    		dfsLevelOrder(root->left, level + 1, ans);
    		dfsLevelOrder(root->right, level + 1, ans);
    	}
    };

Log in to reply
 

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