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

按之字形顺序打印二叉树

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) {
        vector<vector<int> > v;
        queue<TreeNode*> q;
        if(!pRoot)return v;
        q.push(pRoot);
        int k = 1;
        while(!q.empty()){
            TreeNode* tmp;
            vector<int> t;
            int len = q.size();
             while(len--){
                    tmp = q.front();
                    q.pop();
                    t.push_back(tmp->val);
                    if(tmp->left)
                        q.push(tmp->left);
                    if(tmp->right)
                         q.push(tmp->right);
             }       
            if(k%2 == 0)//偶数层反转
                reverse(t.begin(),  t.end());
             v.push_back(t);
             ++k;
        }
        return v;
    }
    
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务