按之字形顺序打印二叉树(层次遍历&标记是知否翻转)

按之字形顺序打印二叉树

http://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > ans;
        if(!pRoot) return ans;
        queue<TreeNode *> q;
        q.push(pRoot);
        int flag = 1;  // 标记是否翻转
        while(!q.empty()){
            int size = q.size();
            flag = flag^1; 
            vector<int> tmp;
            while(size--){
                TreeNode *r = q.front();
                q.pop();
                tmp.push_back(r->val);
                if(r->left) q.push(r->left);
                if(r->right) q.push(r->right);
            }
            if(flag) reverse(tmp.begin(), tmp.end()); // 翻转
            ans.push_back(tmp);
        }

        return ans;

    }

};
全部评论

相关推荐

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