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

求二叉树的层序遍历

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) {
        // write code here
        if (!root) {
            return {};
        }
        std::vector<vector<int>> res;
        std::queue<TreeNode*> q;
        q.push(root);
        q.push(NULL);
        std::vector<int> tmp;
        while (q.size() >= 2) {
            auto t = q.front();
            if (!t) {
                res.push_back(tmp);
                tmp.clear();
                q.push(NULL);
            }
            q.pop();
            if (t) {
                tmp.push_back(t->val);
                if (t->left) {
                    q.push(t->left);
                }
                if (t->right) {
                    q.push(t->right);
                }
            }
        }
        res.push_back(tmp);

        return res;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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