2016-03-14 89 views
0

我已經知道如何遞歸地實現這個函數。這是我的:你如何迭代計算BST(C++)中的節點?

int nodeCount(node *root){ 
    if(root == NULL) 
     return 0; 
    return 1 + nodeCount(root->left) + nodeCount(root->right); 
} 

我現在想執行節點計數沒有遞歸。

+0

爲什麼你不想使用遞歸? – user463035818

+2

如果沒有遞歸,您需要將需要查看的節點存儲在數據結構(如堆棧或隊列)中。那時你基本上在做「手動」遞歸。 – Kevin

+0

我試圖完全理解遞歸與迭代的優點,缺點和實現。我試圖無情地尋找這個代碼的迭代版本,但沒有成功。我只是不知道它是什麼樣子或者它會如何工作。 – CaptainAmericode

回答

1

例如使用stackqueue

Btw。你可能想看看Tail recursion wiki page

int nodeCount(node * root) 
{ 
    int counter = 0; 
    stack<node*> v; // a container with remaining nodes "to check" 
    v.push(root); // first node "to check" 
    while (v.size() > 0) // while there is something "to check" 
    { 
     node * n = v.top(); // take element from the top of stack 
     v.pop(); // remove that element from the top of stack 
     if (n != NULL) // if node is valid 
     { 
      counter++; // count it 
      v.push(n->left); // and add 
      v.push(n->right); // his children to the stack 
     } 
    } 
    return counter; 
} 
+0

放鬆:)被盲目編碼 – Scony

+0

@JamesRoot然後,你會如何解決這個問題'n == nullptr'?在循環之前添加'if(root == NULL)return 0;'之類的東西? – CaptainAmericode

+0

@CaptainAmericode舊評論,現在無關緊要。 –