剑指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) {
        vector<vector<int> > res;
        if (pRoot == NULL){
            return res;
        }
        stack<TreeNode*> stack1;
        stack<TreeNode*> stack2;
        bool flags = true;
        stack1.push(pRoot);
        while (!stack1.empty() || !stack2.empty()){
            if (flags == true){
                vector<int> tmp;
                while (!stack1.empty()){
                    tmp.push_back(stack1.top()->val);
                    
                    if(stack1.top() -> left != NULL){
                        stack2.push(stack1.top()-> left);
                    }
                    if (stack1.top() -> right != NULL){
                        stack2.push(stack1.top()-> right);
                    }
                    stack1.pop();
                }
                res.push_back(tmp);
                flags = false;
            }
            else{
                vector<int> tmp;
                while (!stack2.empty()){
                    tmp.push_back(stack2.top()->val);
                    
                    if (stack2.top() -> right != NULL){
                        stack1.push(stack2.top() -> right);
                    }
                    if (stack2.top() -> left != NULL){
                        stack1.push(stack2.top() -> left);
                    }
                    stack2.pop();
                }
                res.push_back(tmp);
                flags = true;
            }
             
        }
        return res;
    }
     
};

 

posted @ 2017-07-19 11:34  爱简单的Paul  阅读(168)  评论(0编辑  收藏  举报