59、按之字形顺序打印二叉树

(个人水平有限,请见谅!)

题目描述:

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

代码示例:

/*
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>> res;
        if (!pRoot) return res;
        queue <TreeNode*> q;
        q.push(pRoot);
        bool flag = true;
        while (!q.empty())
        {
            vector <int> temp;
            int size = q.size();
            for (int i = 0; i < size; i++)
            {
                temp.push_back(q.front()->val);
                if (q.front()->left != NULL)
                    q.push(q.front()->left);
                if (q.front()->right != NULL)
                    q.push(q.front()->right);
                q.pop();
            }
            if (!flag) reverse(temp.begin(), temp.end());
            res.push_back(temp);
            flag = !flag;
        }
        return res;
    }
    
};

猜你喜欢

转载自blog.csdn.net/qq_30534935/article/details/87909729