当前位置:网站首页>Nine degree 1201 - traversal of binary sort number - binary sort tree "suggestions collection"

Nine degree 1201 - traversal of binary sort number - binary sort tree "suggestions collection"

2022-07-07 21:24:00 Full stack programmer webmaster

Hello everyone , I meet you again , I'm the king of the whole stack .

This is an orthodox tree construction and traversal problem . At the beginning, I also wanted to use array construction to replace the past , But I can't find it , Just use the pointer honestly . If the binary sort tree and traversal method are not clearly defined . It's best to read the data structure book and review .

#include<stdio.h>

struct node{
    node *l;
    node *r;
    int val;
    node(int a):val(a),l(NULL),r(NULL){};
};
node *root;
int n;
void qian(node *p){
    printf("%d ",p->val);
    if(p->l!=NULL)qian(p->l);
    if(p->r!=NULL)qian(p->r);
}
void zhong(node *p){
    if(p->l!=NULL)zhong(p->l);
    printf("%d ",p->val);
    if(p->r!=NULL)zhong(p->r);
}
void hou(node *p){
    if(p->l!=NULL)hou(p->l);
    if(p->r!=NULL)hou(p->r);
    printf("%d ",p->val);
}
 
int main(){
     
    int val;
    node *p;
    while(~scanf("%d",&n)){
        root=NULL;
        for(int i=0;i<n;i++){
            scanf("%d",&val);
            if(i==0){
                root=new node(val);
                continue;
            }
            p=root;
            while(1){
                if(val==p->val)break;
                else if(val<p->val){
                    if(p->l==NULL){
                        p->l=new node(val);
                        break;
                    }
                    else{
                        p=p->l;continue;
                    }
                }
                else if(val>p->val){
                    if(p->r==NULL){
                        p->r=new node(val);
                        break;
                    }
                    else{
                        p=p->r;continue;
                    }
                }
            }
        }   
        qian(root);
        printf("\n");
        zhong(root);
        printf("\n");
        hou(root);
        printf("\n");
    }
    return 0;
}

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/116527.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071810287155.html