32.3 按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0?tpId=13&tqId=11212&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&from=cyc_github&tab=answerKey

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    struct nd{
        TreeNode* node;
        int deep;
        nd(TreeNode* node, int deep): node(node), deep(deep){}
    };
    vector<vector<int> > Print(TreeNode* pRoot) {
        if(pRoot == nullptr) return  vector<vector<int>>{};
        vector<vector<int>> ans;
        ans.push_back(vector<int>{});

        queue<nd> q;
        int currentDeep=1;
        q.push(nd(pRoot, 1));
        while(!q.empty()){
            auto ndnow = q.front();
            q.pop();
            if(ndnow.deep > currentDeep){
                ans.push_back(vector<int>{});
                currentDeep = ndnow.deep;
            }
            ans.back().push_back(ndnow.node->val);
            if(ndnow.node->left){
                q.push(nd(ndnow.node->left, ndnow.deep+1));
            }
            if(ndnow.node->right){
                q.push(nd(ndnow.node->right, ndnow.deep+1));
            }
        }
        for(int i=0;i<ans.size();++i){
            if(i&1){
                reverse(ans[i].begin(), ans[i].end());
            }
        }
        return ans;

    }

};
posted @ 2021-03-28 13:51  rxh1999  阅读(22)  评论(0编辑  收藏  举报