33:按之字形顺序打印二叉树

vector > Print(TreeNode* pRoot) {
        vector>ans;
        stackst1,st2;
        if(pRoot)st1.push(pRoot);
        while(!st1.empty()||!st2.empty())
        {
            vectortemp;
            TreeNode*top;
            if(!st1.empty())
            {
                while(!st1.empty())
                {
                    top=st1.top();
                    st1.pop();
                    temp.push_back(top->val);
                    if(top->left)st2.push(top->left);
                    if(top->right)st2.push(top->right);
                }
                ans.push_back(temp);
            }
            else if(!st2.empty())
            {
                while(!st2.empty())
                {
                    top=st2.top();
                    st2.pop();
                    temp.push_back(top->val);
                    if(top->right)st1.push(top->right);
                    if(top->left)st1.push(top->left);
                }
                ans.push_back(temp);
            }
        }
        return ans;
    }
class Solution {
public:
    vector > Print(TreeNode* pRoot) {
        vector>ans;
        int level=1;
        if(!pRoot)return ans;
        queueq;
        q.push(pRoot);
        while(!q.empty())
        {
            int size=q.size();
            vectortemp;
            while(size--)
            {
                TreeNode*top=q.front();
                q.pop();
                temp.push_back(top->val);
                if(top->left)q.push(top->left);
                if(top->right)q.push(top->right);
            }
            if(level%2==0)reverse(temp.begin(),temp.end());
            level++;
            ans.push_back(temp);
        }
        return ans;
    }
};

你可能感兴趣的:(33:按之字形顺序打印二叉树)