【劍指offer】題61:之字打印二叉樹


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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章