Cattle off - print font in the order of a binary tree

Title Description
Please implement a function according to a binary tree zigzag print, i.e., the first row from left to right order of printing, the print order of the second layer is from right to left, the third row from left to right order of printing, other line and so on.
Solution:
1, odd-numbered rows from left to right, right to left even rows
2, the print order of the LM KJIH DEFG CB A
. 3, define a stack, save the current layer node
4, a queue is defined, for the stack pointer, the odd line holds about a child node, saving even lines right and left child node
Here Insert Picture Description

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        stack<TreeNode*> S;
        queue<TreeNode*> Q;
        S.push(pRoot);
        TreeNode* tmp;
        vector<vector<int> > array;//所有层结点值顺序
        vector<int> line_val;//每层结点值顺序
        int line = 1;//标记奇偶层
        
        if (pRoot==NULL)
            return array;
        
        while (!S.empty())
        {
            line_val.clear();
            while (!S.empty())
            {
                tmp = S.top();
                S.pop();
                line_val.push_back(tmp->val);
                if (line % 2 != 0)
                {
                    if (tmp->left)
                        Q.push(tmp->left);
                    if (tmp->right)
                        Q.push(tmp->right);
                }
                else
                {
                    if (tmp->right)
                        Q.push(tmp->right);
                    if (tmp->left)
                        Q.push(tmp->left);
                }
            }
            while (!Q.empty())
            {
                S.push(Q.front());
                Q.pop();
            }
            line += 1;
            array.push_back(line_val);
        }
        return array;
    }
};
Published 315 original articles · won praise 119 · views 110 000 +

Guess you like

Origin blog.csdn.net/w144215160044/article/details/104941807