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

求二叉树的层序遍历

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

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

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();
                q.pop();
                row.push_back(cur->val);
                if(cur->left){
                    q.push(cur->left);
                }
                if(cur->right){
                    q.push(cur->right);
                }
            }
            res.push_back(row);
        }
        return res;
        // write code here
    }
};

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

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();
                q.pop();
                row.push_back(cur->val);
                if(cur->left){
                    q.push(cur->left);
                }
                if(cur->right){
                    q.push(cur->right);
                }
            }
            res.push_back(row);
        }
        return res;
        // write code here
    }
};

全部评论

相关推荐

学不完不睡觉11:一眼点评,不过,看运气吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务