按照之字形打印二叉树

来源:互联网 发布:端口查看 编辑:程序博客网 时间:2024/05/20 14:28
#include <string>#include <iostream>#include <vector>#include <cstring>#include <stack>using namespace std;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>> ret;        if(pRoot==NULL)            return ret;        stack<TreeNode*> s1;        stack<TreeNode*> s2;        bool flag=true;        s1.push(pRoot);        while(!s1.empty()||!s2.empty())        {            if(flag)//从左边到右访问            {                vector<int> cur;                while(!s1.empty())                {                    TreeNode *temp=s1.top();                    s1.pop();                    cur.push_back(temp->val);                    if(temp->left!=NULL)                        s2.push(temp->left);                    if(temp->right!= NULL)                        s2.push(temp->right);                }                ret.push_back(cur);                flag=!flag;            }else//从右到左边访问            {                vector<int> cur;                while(!s2.empty())                {                    TreeNode *temp=s2.top();                    s2.pop();                    cur.push_back(temp->val);                    if(temp->right!=NULL)                        s1.push(temp->right);                    if(temp->left!=NULL)                        s1.push(temp->left);                }                ret.push_back(cur);                flag=!flag;            }        }        return ret;    }};
1 0
原创粉丝点击