C++ 4ms simple recursive solution


  • 7
    S
    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);
    }
    };

  • 0

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


  • 0

    Easy to understand! Thanks!


  • 0
    K

    Any idea about the below sentence which cannot pass

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


  • 0
    S

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


  • 0
    K
    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);
    }
    };

  • 0
    K

    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?


  • 0
    S

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


  • 0
    K

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


  • 0
    S

    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?


  • 0
    L

    @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.


  • 0
    R

    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?


Log in to reply
 

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