【发布时间】:2019-12-04 13:32:44
【问题描述】:
我想用 C 计算这个函数的复杂度。 这是一棵普通的树
struct nodeG {
int key;
struct nodeG *left_child;
struct nodeG *right_sib;
};
int aux (NodeG u) {
int current = 1; // O(1)
int childs = 0; // O(1)
while (u) { // O(k)
if (u-> left_child) // O(1)
childs += aux (u-> left_child); // O(1)
if (u->right_sib && current && u->key < u->right_sib->key) // O(1)
current = 0; // O(1)
u = u -> right_sib; // O(1)
}
return current + childs; // O(1)
}
【问题讨论】:
-
您访问所有节点一次,所以它是 O(N) 其中 N=树中的节点数。顺便提一下,您的算法与 DFS 非常相似,您用于停止搜索的条件是您在当前子树的空节点处,因此您将访问所有节点。
-
您有一行代码
childs += aux (u-> left_child);,您已将其注释为// O(1),因此您似乎已经决定aux函数在O(1) 时间内运行。当然不是。
标签: algorithm data-structures time-complexity