把二叉树打印成多行

把二叉树打印成多行

https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

//与按之字形打印二叉树题目相同,应用队列实现二叉树的打印

/*
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>> ans;
            if(!pRoot) return ans;
            queue<TreeNode*> q;
            q.push(pRoot);
            while(!q.empty())
            {
                vector<int> tmp;
                int n = q.size();
                for(int i =0;i<n;i++)
                {
                    TreeNode* node = q.front();
                    q.pop();
                    tmp.push_back(node->val);
                    if(node->left) q.push(node->left);
                    if(node->right) q.push(node->right);
                }
                ans.push_back(tmp);
            }
            return ans;
        }
};
全部评论

相关推荐

牛客410815733号:这是什么电影查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务