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

按之字形顺序打印二叉树

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) {
    }
};
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> res;
        if(pRoot==nullptr) return res;
        queue<TreeNode *> q;
        q.push(pRoot);
        TreeNode *cur;
        int flag=1;
        while(!q.empty()){
            int n=q.size();
            vector<int>row;
            for(int i=0;i<n;++i){
            cur=q.front();
            q.pop();
            row.push_back(cur->val);
            if(cur->left){
                q.push(cur->left);
            }
            if(cur->right){
                q.push(cur->right);
            }
            }
            if(flag%2==0){
                reverse(row.begin(),row.end());
            }
            res.push_back(row);
            flag++;
        }
        return res;
    }
    
};

全部评论

相关推荐

牛客717484937号:双飞硕没实习挺要命的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务