[剑指offer] 59. 按之字形顺序打印二叉树

题目描述

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

思路:
用两个栈或队列去存储,用一个变量表示方向,根据不同方向存取顺序不同。
class Solution
{
  public:
    vector<vector<int>> Print(TreeNode *pRoot)
    {
        vector<vector<int>> res;
        if (pRoot == NULL)
            return res;

        int direct = 1;
        stack<TreeNode *> staO;
        stack<TreeNode *> staE;
        TreeNode *cur;
        
        staO.push(pRoot);
        while (!staO.empty() || !staE.empty())
        {
            vector<int> temp;
            if (direct % 2 != 0)
            {
                while (!staO.empty())
                {
                    cur = staO.top();
                    staO.pop();
                    temp.push_back(cur->val);
                    if (cur->left != NULL)
                        staE.push(cur->left);
                    if (cur->right != NULL)
                        staE.push(cur->right);
                }
                res.push_back(temp);
                direct = 2;
            }
            else
            {
                while (!staE.empty())
                {
                    cur = staE.top();
                    staE.pop();
                    temp.push_back(cur->val);
                    if (cur->right != NULL)
                        staO.push(cur->right);
                    if (cur->left != NULL)
                        staO.push(cur->left);
                }
                res.push_back(temp);
                direct = 1;
            }
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/ruoh3kou/p/10244723.html