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

按之字形顺序打印二叉树

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

相关推荐

缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
企业都这么缺人了吗?缺人为什么还给白菜价!
真起不了响亮的名字:我给你出个主意,把公司报出来,让牛友去投,岂不美哉
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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