C++ 4ms simple recursive solution

• ``````class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> result;
recur_levelOrder(result, root, 0);
return result;
}

void recur_levelOrder(vector<vector<int>> &result, TreeNode *root, int level)
{
if (!root)
{
return;
}
if ((level+1) > result.size())
{
result.push_back(vector<int> {});
}
result[level].push_back(root->val);
recur_levelOrder(result, root->left, level+1);
recur_levelOrder(result, root->right, level+1);
}
};``````

• Nice solution with level-oriented, man - thanks for sharing!

• Easy to understand! Thanks!

• Any idea about the below sentence which cannot pass

if ((level) > result.size()-1)

• Can you please post all your codes here? So that we can try to find problems.

• ``````class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int> > result;
levelOrder_recur(result, root, 0);
return result;
}

void levelOrder_recur(vector<vector<int> >& result, TreeNode* root, int level) {
if (!root) { return; }
if (level > (result.size()-1)) { result.push_back(vector<int>{}); }
result[level].push_back(root -> val);
levelOrder_recur(result, root -> left, level+1);
levelOrder_recur(result, root -> right, level+1);
}
};``````

• BTW, just realized, if I write function without indent below "public:", it is much faster than with indent which is a normal way. Do you understand the reason?

• Ur code looks fine, sorry I don't know why it cannot pass :|. And I don't either know nothing about indent and performance.

• Did u try to copy and run this? Wonder if only me having this issue.

• Hi! I try your code and the issue does occur. However, when you declare result.size() as a new var separately, for example:

``````int s=result.size();
if (level > s-1) { result.push_back(vector<int>{}); }
``````

then everything works. Can anybody explain it?

• @scnuysc because result.size() is an unsigned int, and the result of result.size()-1 is unsigned too. So when result is empty, result.size() is zero, and result.size()-1 is not -1 but a large number. If you use int s = result.size(), when result is empty, the output s - 1 is -1, so it will work.

• `if ( level +1 > result.size()) { result.push_back(vector<int>{});`

Just to clarify the meaning of this line. If the current height is less than the current height of the vector, we add an empty row. to level it out. Can you please explain?

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