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

按之字形顺序打印二叉树

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>
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> res;
        if (pRoot == nullptr) return res;
        queue<TreeNode*> q;
        q.push(pRoot);
        bool direction = true;  // 用于控制打印方向
        while (!q.empty()) {
            int size = q.size();
            vector<int> row_vec;
            for (int i = 0; i < size; ++i) {
                TreeNode* tmp = q.front();
                q.pop();
                row_vec.push_back(tmp->val);
                if (tmp->left) q.push(tmp->left);
                if (tmp->right) q.push(tmp->right);
            }
            if (!direction) {
                reverse(row_vec.begin(), row_vec.end());
                for (int i = 0; i < row_vec.size(); ++i) {
                    cout << "----- " << row_vec[i];
                }
                cout << endl;
            }
            res.push_back(row_vec);
            direction = !direction;
        }
        return  res;
    }
    
};
2023-剑指-二叉树 文章被收录于专栏

2023-剑指-二叉树

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务