【发布时间】:2015-03-24 23:36:50
【问题描述】:
你能帮我理解计算以下函数的时间和空间复杂度吗?
函数(): 作用:在每一层创建节点向量
- 创建一个队列。
- 添加根
- 将队列中的元素复制到向量中。
- 遍历向量并将子项(左和右)附加到队列中。
- 重复步骤 3 和 4,直到队列为空。
下面是代码。
struct node {
int value;
struct node* p_left;
struct node* p_right;
};
void levels_list(struct node* p_btree) {
if(!p_btree) {
return ;
}
std::queue<struct node*> q;
std::vector<std::vector<struct node*> > v1;
q.push(p_btree);
bool choice = false;
while(!q.empty()) {
std::vector<struct node*> v;
while(!q.empty()) {
v.push_back(q.front());
q.pop();
}
for(int i = 0; i < v.size(); i++) {
if(v[i]->p_left) {
q.push(v[i]->p_left);
}
if(v[i]->p_right) {
q.push(v[i]->p_right);
}
}
v1.push_back(v);
v.clear();
}
}
我看到它是 O(n^2),对吗? 有两个循环,第一个是外部循环,第二个是内部循环,它将元素从队列中推入向量中。
谢谢
【问题讨论】: