LeetCode-103: traverse the binary tree hierarchy serrated

One, Title Description

Here Insert Picture Description

Second, problem-solving ideas

Use traverse the level, the current number of records in the queue each time data into the circulation, then the current number is the number of nodes in this layer, plus a boolvariable should be determined whether the current rollover

Third, the problem-solving Code

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> sln;
        if(!root)   return sln;
        queue<TreeNode*> q;
        q.push(root);
        bool flag = 0;
        while(!q.empty()){
            auto len = q.size();
            vector<int> ins;
            for(size_t i = 0; i < len; i++){
                auto num = q.front();
                q.pop();
                ins.push_back(num->val);
                if(num->left)   q.push(num->left);
                if(num->right)  q.push(num->right);

            }
            if(flag == 1){
                reverse(ins.begin(), ins.end());
            }
            flag = 1 - flag;
            sln.push_back(ins);
        }
        return sln;
    }
};

Fourth, operating results

Here Insert Picture Description

Published 30 original articles · won praise 3 · Views 809

Guess you like

Origin blog.csdn.net/weixin_44587168/article/details/105376542