【发布时间】:2020-07-31 16:59:31
【问题描述】:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> bfs;
if (root != nullptr) bfs.push(root);
vector<vector<int>> sol;
vector<TreeNode*> temp;
vector<int> indivSol;
while (!bfs.empty()) {
int currSz = bfs.size();
for (int i = 0; i < currSz; i++) {
temp.push_back(bfs.front());
bfs.pop();
indivSol.push_back(temp.at(i)->val);
if (temp.at(i)->left != nullptr) bfs.push(temp.at(i)->left);
if (temp.at(i)->right != nullptr) bfs.push(temp.at(i)->right);
}
temp.clear();
sol.push_back(indivSol);
indivSol.clear();
}
return sol;
}
我知道外部 while 循环将运行 n 次(n 是树中的节点数),但内部 for 循环会使解决方案在 O(n^2) 时间内运行吗?由于一棵树在n 级别上最多有2^n 节点,因此currSz 可以从1 to 2 to 4 to 8 to 16 ... 的外部循环的每次迭代中增长
编辑:
意识到外部循环只会运行l 多次,其中l 是级别数
【问题讨论】:
-
O(n)的解释是什么?
-
n 是什么意思?节点数?等级数?还有什么?