【剑指offer】题61:之字打印二叉树

来源:互联网 发布:淘宝无节操买家秀图片 编辑:程序博客网 时间:2024/05/16 20:28

vector<vector<int>> Print(TreeNode* pRoot){    vector<vector<int>> vec;    if (pRoot== NULL)        return vec;    stack<TreeNode*> my_stack[2];    int cur_deep(0);    int next_deep(1);    my_stack[cur_deep % 2].push(pRoot);    while (!my_stack[cur_deep%2].empty())    {        vec.push_back(vector<int>());        while (!my_stack[cur_deep%2].empty())        {            TreeNode* tmp = my_stack[cur_deep % 2].top();            vec.back().push_back(tmp->val);            my_stack[cur_deep % 2].pop();            if (cur_deep % 2 == 0)            {                if (tmp->left != NULL)                {                    my_stack[next_deep % 2].push(tmp->left);                }                if (tmp->right != NULL)                {                    my_stack[next_deep % 2].push(tmp->right);                }            }            else            {                if (tmp->right != NULL)                {                    my_stack[next_deep % 2].push(tmp->right);                }                if (tmp->left != NULL)                {                    my_stack[next_deep % 2].push(tmp->left);                }            }        }        cur_deep++;        next_deep++;    }    return vec;}

原创粉丝点击