题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

#include <iterator>
#include <vector>
class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if(root==nullptr) return ans ;
        queue<TreeNode*> Q;
        Q.push(root);
        vector<int>t;
        while(!empty(Q)){
            int size=Q.size();
            while(size--){
                root=Q.front();
                Q.pop();
                t.push_back(root->val);
                if(root->left) Q.push(root->left);
                if(root->right) Q.push(root->right);
            }
            ans.push_back(t);
            t.clear();
        }
        return ans;
    }
};

全部评论

相关推荐

07-17 11:56
门头沟学院 Java
感谢东子的收留
码农索隆:好好好,优秀优秀
点赞 评论 收藏
分享
06-23 11:28
门头沟学院 Java
牛客91966197...:也有可能是点拒绝的时候自动弹的话术
点赞 评论 收藏
分享
06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务