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

求二叉树的层序遍历

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

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if( root == nullptr) return res;

        queue<TreeNode*> q;
        q.push(root);

        TreeNode* cur;
        while(!q.empty()){
            vector<int> row;
            int n = q.size();
            for (int i = 0; i < n; i++){
                cur = q.front();
                row.push_back(cur->val);
                q.pop();
                if(cur->left != nullptr) q.push(cur->left);
                if(cur->right != nullptr) q.push(cur->right);
            }
            res.push_back(row);
        }

        return res;
    }
};

用for循环记录一下每一层的元素个数

队列queue<typename>;

push();

front();

back();

pop();

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务