题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
#include <algorithm>
#include <queue>
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        queue<TreeNode *> q;
        vector<vector<int> > res;
        if (pRoot) {
            q.push(pRoot);
        }
        int idx = 0;
        while (!q.empty()) {
            int n = q.size();
            vector<int> tmp;
            for (int i = 0; i < n; ++i) {
                auto now = q.front();
                q.pop();
                tmp.push_back(now->val);
                if (now->left) {
                    q.push(now->left);
                }
                if (now->right) {
                    q.push(now->right);
                }
            }
            if (idx % 2) {
                reverse(tmp.begin(), tmp.end());
            }
            res.push_back(tmp);
            ++idx;
        }
        return res;
    }
    
};

思路:层序遍历

* 层序遍历模板

* 因为要之字形遍历,所以增加一个计数表示当前层数,从0开始

* 当前层数为奇数时,将当前层的遍历反向

全部评论

相关推荐

流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务