C++/代码:

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> res; //定义二维数组
        vector<int> level; 
        if (!pRoot) return res;
        queue<TreeNode*> q;
        q.push(pRoot);
        q.push(NULL);
        bool zigzag = false; //false则从左到右打印,true则从右到左打印
        while (q.size()) {
            auto t = q.front();
            q.pop();
            if(!t){
                if (level.empty()) break;
                if (zigzag) reverse(level.begin(),level.end());
                res.push_back(level);
                q.push(NULL);
                level.clear();
                zigzag = !zigzag;
                continue;
            }
            level.push_back(t->val);
            if (t->left) q.push(t->left);
            if (t->right) q.push(t->right);
        }
        return res;
    }
};