C++/代码:

按之字形顺序打印二叉树

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

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;
    }
};
全部评论

相关推荐

Aaso:挺好的,早挂早超生
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务