1.层次遍历



title: 层次遍历


?? 题目描述

题目链接:二叉树的层次遍历

?? 解题思路

简简单单,用队列来保存每一层的数量,再进行遍历。

class Solution {
public:
    vector> levelOrder(TreeNode* root) {
        if (!root) return{};
        queue que;
        vector> res;
        que.push(root);
        while (!que.empty()) {
            vector path;
            int len = que.size();
            for (int i = 0; i < len; i++) {
                TreeNode* node = que.front();//获取值
                que.pop();
                path.push_back(node->val);
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
            res.push_back(path);
        }
        return res;
    }
};

?? 复杂度分析

  • 空间复杂度:O(n)
  • 时间复杂度:O(n)