32.2 把二叉树打印成多行

https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&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 d):node(node), deep(d){}
    };
        vector<vector<int> > Print(TreeNode* pRoot) {
            if(pRoot == nullptr) return vector<vector<int>>{};
            queue<nd> q;
            q.push(nd(pRoot, 1));
            int currentDeep = 1;
            vector<vector<int>> ans;
            ans.push_back(vector<int>{});
            while(!q.empty()){
                auto ndnow = q.front();
                if(ndnow.deep > currentDeep){
                    //new
                    currentDeep = ndnow.deep;
                    ans.push_back(vector<int>{});
                }
                ans.back().push_back(ndnow.node->val);
                q.pop();
                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));
                }
            }
            return ans;
        }
    
};
posted @ 2021-03-28 13:36  rxh1999  阅读(54)  评论(0编辑  收藏  举报