简体   繁体   English

将二叉树排序到排序数组中

[英]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. SRD是左,根,右交叉,并且adaugare是插入功能。 So if i go with cout << rad -> info << " "; 因此,如果我使用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 在SRD函数中它可以工作,但是在数组中不起作用:( ..我认为问题出在SRD函数中,所以有什么需要帮助吗?(当它应该在像这样的二叉树中打印2 3 4 6 7 8时,它只打印7 (根)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]) 而(A [k]的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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