簡體   English   中英

將二叉樹排序到排序數組中

[英]Sorting Binary tree into a sorted array

我的代碼有問題,請提供一些幫助嗎?

完整代碼:

#include <iostream>

using namespace std;  
int a[100],k;  
struct nod  
            {  
             int info;  
             nod *st,*dr;  
            } *rad,*p;  


void adaug(nod *&rad, int x)  
{  
    if(!rad)  
            {  
             nod *p = new nod;  
             p -> info = x;  
             p -> st = 0;  
             p -> dr = 0;  
             rad = p;  
            }  
        else if(x < rad -> info)    adaug(rad->st,x);  
                  else              adaug(rad->dr,x);  
}  

void SRD(nod *rad,int &k)  
{  
    if(rad)  
            {  
             SRD(rad -> st,k);  
             a[k] = rad -> info;  
             k++;  
             SRD(rad -> dr,k);  
            }  
}  


int main()  
{  
    nod *rad = NULL;  
    int n,x,i;  
    cout << "n="; cin >> n;  
    for(i = 1; i <= n; i++)  
    {  
        cin >> x;  
        adaug(rad,x);  
    }  

SRD(rad,k);

while (a[k]){  
             cout << a[k] << " ";  
             k++;  
             }  
cout << endl << k;  
    return 0;  
}  

SRD是左,根,右交叉,並且adaugare是插入功能。 因此,如果我使用cout << rad-> info <<“”; 在SRD函數中它可以工作,但是在數組中不起作用:( ..我認為問題出在SRD函數中,所以有什么需要幫助嗎?(當它應該在像這樣的二叉樹中打印2 3 4 6 7 8時,它只打印7 (根)3 8 2 4 7 9

做這個...

for(i = 0; i < k; i++)
 cout<<a[i]<<" ";

或者像這樣

i=0;
while(i<k)
{
    cout<<a[i]<<" ";
    i++;
}

您的代碼中的問題是

而(A [k]的)

暫無
暫無

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

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