2012-08-06 71 views
0

我有一個遍歷級順序的AVL樹的函數。輸出格式爲:在遞歸函數中保持計數C++

level 0: jim(2) 
level 1: bob(1) joe(1) 

但是當我到4級了,我要打破它,所以它只會顯示每行8個項目。所以出來看起來是這樣的:

level 4: item1(1) item2(1) item3(2) item4(2) item5(1) item6(2) item7(1) item8(2) 
level 4: item9(2) item10(2) 

現在我的代碼將顯示所有的項目,但只在一行。我無法弄清楚如何改進這些代碼,以便按照我想要的格式進行格式化。我怎樣才能實現這個?

以下是當前功能:

//PRINT BY LEVEL ORDER TRAVERSAL 
void Avltree::level_order(Avlnode* root, ofstream &out){ 
int h = height(root); 
for(int i = 0; i < h; i++){ 
    out << "Level " << i << ": "; 
    print_level(root, i, out); 
    out << endl; 
} 
} 

//PRINT A GIVEN LEVEL ON A TREE 
void Avltree::print_level(Avlnode* root, int level, ofstream &out){ 

    if(root == NULL) 
     return; 
    if(level == 0){ 
     out << root->data << "(" << height(root) << ") "; 
    } 
    else if (level > 0) 
    { 
     print_level(root->left, level-1, out); 
     print_level(root->right, level-1, out); 
    } 
} 

回答

2

你應該通過計數作爲參數傳遞給遞歸函數,當計數%8(或任何你想要的每行要數)爲0,則開始新的一行。

+0

謝謝!我不確定爲什麼當我這樣做時它不工作,但它現在起作用。謝謝。 – Jordan 2012-08-06 17:22:54

2

引用參數添加呼叫爲節點總數印刷

void Avltree::print_level(Avlnode* root, int level, ofstream &out, int &count) 
{ 
    ... 
    if(level == 0){ 
     out << root->data << "(" << height(root) << ") "; 
     count++; 
    } 
    if(count==8){ 
     out << endl; 
     count=0; 
    } 
    ... 
} 

而主叫將

int count=0; 
for(int i = 0; i < h; i++){ 
    count=0; 
    out << "Level " << i << ": "; 
    print_level(root, i, out, count); 
    out << endl; 
} 
+0

謝謝!這太棒了!不知道爲什麼它以前沒有工作 – Jordan 2012-08-06 17:33:27