Niuke.com Jianzhi offer-print binary tree in zigzag order

topic description

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


/*
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) {
        vector<vector<int> > ans;
        stack<TreeNode*> sta1, sta2;
        if (pRoot == nullptr)
            return ans;
        sta1.push(pRoot);
        vector<int> vec;
        while (!sta1.empty())
        {
            vec.clear();
            while (!sta1.empty())
            {
                if (sta1.top()->left != nullptr)
                    sta2.push(sta1.top()->left);
                if (sta1.top()->right != nullptr)
                    sta2.push(sta1.top()->right);
                vec.push_back(sta1.top()->val);
                sta1.pop();
                if (sta1.empty())
                    ans.push_back(vec);
            }
            vec.clear();
            while (!sta2.empty())
            {
                if (sta2.top()->right != nullptr)
                    sta1.push(sta2.top()->right);
                if (sta2.top()->left != nullptr)
                    sta1.push(sta2.top()->left);
                vec.push_back(sta2.top()->val);
                sta2.pop();
                if (sta2.empty())
                    ans.push_back(vec);
            }
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/yhn19951008/article/details/79434164