题解 | #把二叉树打印成多行# | C++

把二叉树打印成多行

https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <queue>
#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> ans;
        if (pRoot == nullptr) return ans;
        std::queue<TreeNode*> q;
        q.push(pRoot);
        while (!q.empty()) {
            int n = q.size();
            vector<int> item;
            while (n-- >= 1) {
                auto front = q.front();
                q.pop();
                item.push_back(front->val);
                if (front->left) {
                    q.push(front->left);
                }
                if (front->right) {
                    q.push(front->right);
                }
            }
            ans.push_back(std::move(item));
        }
        return ans;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
你背过凌晨4点的八股文么:简历挂了的话会是流程终止,像我一样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务