A 8ms Accepted Solution


  • 1
    Y
    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> ans;
            queue<TreeNode*> treeQueue;
            if(root == NULL) return ans;
            treeQueue.push(root);
            int count = 0;
            while(treeQueue.size() != 0) {
                count = treeQueue.size();
                vector<int> line;
                for(int i = 0; i < count; ++i) {
                    TreeNode *temp = treeQueue.front();
                    treeQueue.pop();
                    line.push_back(temp->val);
                    if(temp->left != NULL) treeQueue.push(temp->left);
                    if(temp->right != NULL) treeQueue.push(temp->right);
                }
                ans.push_back(line);
            }
            for(int i = 0; i < ans.size()/2; ++i) {
                ans[i].swap(ans[ans.size() - i - 1]);
            }
            return ans;
        }
    };

  • 0
    2

    very smart idea for caclulating the tree level


  • 0
    Y

    Thank you very much!


  • 0
    2

    maybe you can insert vector<int> line from ans begin


  • 0
    Y

    Using built-in insert function is a direct approach as what our mind think, but it take time. Using insert will take about 60ms.


Log in to reply
 

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