簡體   English   中英

這個函數在 C 中的時間復雜度是多少?

[英]What is the Time-Complexity of this function in C?

我想用 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(1) 操作,因此總運行時間為 O(n),其中 n 是節點數。

更詳細地說,該函數為每個節點的最左邊的子節點調用一次。 while循環然后循環遍歷它的所有兄弟。 所以循環內部每個節點執行一次,或者總共執行 n 次。 除了循環和遞歸調用,其余語句都是 O(1)。 所以這最終需要 O(n) 時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM