牛客网剑指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> > ans;
        stack<TreeNode*> sta1, sta2;
        if (pRoot == nullptr)
            return ans;
        sta1.push(pRoot);
        vector<int> vec;
        while (!sta1.empty())
        {
            vec.clear();
            while (!sta1.empty())
            {
                if (sta1.top()->left != nullptr)
                    sta2.push(sta1.top()->left);
                if (sta1.top()->right != nullptr)
                    sta2.push(sta1.top()->right);
                vec.push_back(sta1.top()->val);
                sta1.pop();
                if (sta1.empty())
                    ans.push_back(vec);
            }
            vec.clear();
            while (!sta2.empty())
            {
                if (sta2.top()->right != nullptr)
                    sta1.push(sta2.top()->right);
                if (sta2.top()->left != nullptr)
                    sta1.push(sta2.top()->left);
                vec.push_back(sta2.top()->val);
                sta2.pop();
                if (sta2.empty())
                    ans.push_back(vec);
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/yhn19951008/article/details/79434164