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

按之字形顺序打印二叉树

http://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;
        queue<TreeNode*> q;
        if(!pRoot)
            return {};
        bool flag = true;
        q.push(pRoot);
        while(!q.empty()){
            int l = q.size();
            vector<int> out(l);
            for(int i=0; i<l; i++){
                TreeNode* t = q.front();
                q.pop();
                int idx = flag ? i : (l - 1 - i);
                out[idx] = t->val;
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
            flag = !flag;
            res.push_back(out);
        }
        return res;
        
    }
    
};

https://www.cnblogs.com/grandyang/p/4297009.html
全部评论

相关推荐

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