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

按之字形顺序打印二叉树

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

class Solution {
public:
    //本质还是bfs,奇数行从左到右,偶数行从右到左
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> >result;
        queue<TreeNode*>q;
        int level=0;
        if(pRoot==NULL)return result;//防止为空
        q.push(pRoot);
        while(!q.empty()){
            vector<int>ans;
            int size=q.size();//用于记录每一行个数
            while(size--){
                TreeNode* temp=q.front();
                q.pop();
                ans.push_back(temp->val);
                if(temp->left)
                q.push(temp->left);
                if(temp->right)
                q.push(temp->right);
                
            }
            level++;
            if(!(level&1)){reverse(ans.begin(),ans.end());}//偶数要反转
         result.push_back(ans);
        }
        return result;
    }
    
};
全部评论

相关推荐

钱嘛数字而已:辅导员肯定不能同意,不然你出事了,他要承担责任。但是,脚和脑子都长在你自己身上,使用它还需要向辅导员报告么? 辅导员必须按流程拒绝你,然后你拿出成年人的态度,做自己的选择。
点赞 评论 收藏
分享
01-17 11:57
已编辑
门头沟学院 前端工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务