简体   繁体   中英

Sorting Binary tree into a sorted array

i have a problem with my code,a little help please ?:D

FULL CODE:

#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 is left,root,right crossing,and adaugare is the insertion function. So if i go with cout << rad -> info << " "; in SRD function it works but with array doesn`t :(. I think the problem is in SRD function so any help please?(it prints only 7 when it should print 2 3 4 6 7 8 in a binary tree like this: 6 (root) 3 8 2 4 7 9

Do like this...

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

Or like this

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

The problem in your code is with

while(a[k])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM