剑指offer32-III.从上到下打印二叉树(之字型打印)

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if (root == NULL) return ans;
        queue<TreeNode*> q;
        q.push(root);
        ans.push_back({root->val});
        int fl = 0;
        while(!q.empty()) {
            int n = q.size();
            vector<int> vec;
            for (int i = 0; i < n; i++) {
                auto p = q.front();
                if (p->left) {
                    vec.push_back(p->left->val);
                    q.push(p->left);
                }
                if (p->right) {
                    vec.push_back(p->right->val);
                    q.push(p->right);
                }
                q.pop();  
            }
            if (vec.size()) {
                if (fl % 2 == 0) reverse(vec.begin(), vec.end()); 
                ans.push_back(vec);
            }
            fl++;
        }
        return ans;
    }
};

全部评论

相关推荐

评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务