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

Source

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

题目描述

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

解题思路

我大概是看书看傻了,书上的方法记混了,一会想用栈,一会想先存左子树再存右子树下一层相反,还好最后冷静分析,奇数层顺序遍历,偶数层用栈存。注意一开始传入空指针的情况。。引发段错误。。

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) {
        vector<vector<int> > result;
        if(!pRoot) return result;
        vector<int> layer;
        queue<TreeNode*> q;
        stack<int> temps;
        int currentLayerCount = 1, nextLayerCount = 0, flag = 0;
        q.push(pRoot);
        while(!q.empty()) {
            TreeNode* currentTreeNode = q.front();
            q.pop();
            currentLayerCount--;
            if(flag) {
                temps.push(currentTreeNode->val);
            } else {
                layer.push_back(currentTreeNode->val);
            }
            if(currentTreeNode->left) {
                    q.push(currentTreeNode->left);
                    nextLayerCount++;
            }
            if(currentTreeNode->right) {
                    q.push(currentTreeNode->right);
                    nextLayerCount++;
            }
            if(!currentLayerCount) {
                currentLayerCount = nextLayerCount;
                nextLayerCount = 0;
                if(flag) {
                    while(!temps.empty()) {
                        layer.push_back(temps.top());
                        temps.pop();
                    }
                }
                result.push_back(layer);
                layer.clear();
                flag = 1-flag;
            }
        } 
        return result;
    }
    
};