Leetcode|二叉树的遍历方式|102. 二叉树的层序遍历

2021-09-18 15:26:36 浏览数 (1)

BFS

代码语言:javascript复制
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if (!root) return {};
        vector<vector<int>> vec2d;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int sz = q.size();
            vector<int> vec1d;
            for (int i=0;i < sz;i  ) {
                auto node = q.front(); q.pop();
                vec1d.push_back(node->val);
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
            vec2d.push_back(vec1d);
        }
        return vec2d;
    }
};

这里再积累一个二维vector的插入写法,即利用vec2d.back()方法调用二维向量中的一维向量

代码语言:javascript复制
vector<vector<int>> vec2d;
vec2d.push_back(vector<int> ());
vec2d.back().push_back(node->val);

0 人点赞