按之字形顺序打印二叉树

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

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};

思路一:使用队列类似于BFS,但是这里需要加控制转向

vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > res;
        if(pRoot==NULL) return res;
        queue<TreeNode*> qu;//定义一个队列
        qu.push(pRoot);
        bool even=false;
        while(!qu.empty())
        {
            vector<int> vec;
            int size=qu.size();
            for(int i=0;i<size;i++)
            {
                TreeNode *tmp=qu.front();
                qu.pop();
                vec.push_back(tmp->val);//把该节点的值放入栈中
                if(tmp->left!=NULL)
                {
                    qu.push(tmp->left);
                }
                if(tmp->right!=NULL)
                    qu.push(tmp->right);
            }
            if(even)
             {
                reverse(vec.begin(),vec.end());//使用reverse效率比较低
            }
            res.push_back(vec);
            even=!even;
        }
        
        return res;
    }

 

思路二:使用两个栈:stack1储存奇数层,stack2储存偶数层,交替放入。

vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > result;
        stack<TreeNode *> stack1,stack2;
    
        if(pRoot!=NULL)
            stack1.push(pRoot);
        struct TreeNode *node;
        while(!stack1.empty() || !stack2.empty()){
            vector<int> data;
            if(!stack1.empty()){
                while(!stack1.empty()){
                    node = stack1.top();
                    stack1.pop();
                    data.push_back(node->val);
                    if(node->left!=NULL)
                        stack2.push(node->left);
                    if(node->right!=NULL)
                        stack2.push(node->right);
                }
                result.push_back(data);
            }
            else if(!stack2.empty()){
                while(!stack2.empty()){
                    node = stack2.top();
                    stack2.pop();
                    data.push_back(node->val);
                    if(node->right!=NULL)
                        stack1.push(node->right);
                    if(node->left!=NULL)
                        stack1.push(node->left);
                }
                result.push_back(data);
            }
        }
        return result;
    }

 

posted @ 2017-08-30 21:11  泡面小王子  阅读(144)  评论(0编辑  收藏  举报