写在前面

剑指offer:按之字形顺序打印二叉树

题目要求

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

解法

/* 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) {
        if(!pRoot) return vector<vector<int>> ();
        vector<vector<int>> res;
        queue<TreeNode*> q;
        q.push(pRoot);
        TreeNode* tail = pRoot;
        bool tag = false;
        vector<int> v;

        while(!q.empty()) {
            TreeNode* cur = q.front();
            q.pop();
            v.push_back(cur->val);
            if(cur->left) q.push(cur->left);
            if(cur->right) q.push(cur->right);

            if(cur==tail) {
                if(tag) { 
                    reverse(v.begin(),v.end());
                }
                tag = !tag;
                res.push_back(v);
                tail = q.back();
                v.clear();
            }
        }
        return res;
    }

};

分析:
采用队列的方式进行层序遍历,再加上一个tag状态标识是奇数层还是偶数层,如果是偶数层需要翻转。