用队列实现,每次记录下当前队列的大小即可:
// // Created by jt on 2020/8/22. // #include <vector> #include <queue> using namespace std; class Solution { public: /** * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > levelOrder(TreeNode* root) { // write code here vector<vector<int> > res; if (!root) return res; queue<TreeNode *> qu; qu.push(root); while (!qu.empty()) { int size = qu.size(); vector<int> vec; while (size--) { TreeNode *node = qu.front(); qu.pop(); vec.push_back(node->val); if (node->left) qu.push(node->left); if (node->right) qu.push(node->right); } if (vec.size() > 0) res.push_back(vec); } return res; } };