The sword refers to the offer: print the binary tree in zigzag order

Topic description

Please implement a function to print the binary tree in a zigzag pattern, that is, the first line is printed in left-to-right order, the second layer is printed in right-to-left order, the third line is printed in left-to-right order, and the other lines are printed in order from left to right. And so on.

ideas

Similar to printing multiple lines, traverse the layers, use a variable to record the number of nodes in each layer, store the nodes of each layer in a vector, and finally put them in the result. The difference is that this time it is a zigzag, using two A stack is used instead of a queue. One stack starts from the left side of each layer. When popping the stack, the output is from right to left. The other is from the right to left of each layer. When popping the stack, the output is from left to right. order

code

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        stack<TreeNode*>odd;
        stack<TreeNode*>even;
        vector<int>layer;
        vector<vector<int>>res;
        if(pRoot==nullptr)
            return res;
        int i=1,qs=0;
        odd.push(pRoot);
        while(!odd.empty()||!even.empty()){
            if(i%2==1){
                qs=odd.size();
                while(qs--){
                    layer.push_back(odd.top()->val);
                    if(odd.top()->left)
                        even.push(odd.top()->left);
                    if(odd.top()->right)
                        even.push(odd.top()->right);
                    odd.pop();
                }
            }else if(i%2==0){
                qs=even.size();
                while(qs--){
                    layer.push_back(even.top()->val);
                    if(even.top()->right)
                        odd.push(even.top()->right);
                    if(even.top()->left)
                        odd.push(even.top()->left);
                    even.pop();
                }

            }
            res.push_back(layer);
            layer.clear();
            i++;
        }
        return res;
    }

};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324730282&siteId=291194637