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

按之字形顺序打印二叉树

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

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<int>> Print(TreeNode* pRoot) {
        queue<TreeNode*> que;
        vector<vector<int>> res;
        int flag=0;
        if(pRoot==nullptr) return res;
        que.push(pRoot);
        while(!que.empty())
        {
            int s=que.size();
            vector<int> path;
            for(int i=0;i<s;i++)
            {
                auto tmp=que.front();
                path.push_back(tmp->val);
                que.pop();
                if(tmp->left) que.push(tmp->left);
                if(tmp->right) que.push(tmp->right);
            }
            if(flag==0)
            {
                res.push_back(path);
                flag=1;
            }
            else 
            {
                reverse(path.begin(),path.end());
                res.push_back(path);
                flag=0;
            }
        }
        return res;

    }

};
全部评论

相关推荐

06-13 10:15
门头沟学院 Java
想去夏威夷的大西瓜在...:我也是27届,但是我现在研一下了啥项目都没有呀咋办,哎,简历不知道咋写
点赞 评论 收藏
分享
深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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