算法与数据结构考研试题精析-第9章算法设计题23

    xiaoxiao2022-07-07  170

    按递增次序输出排序二叉树中所有大于x的结点数据,分递归版本和非递归版本

    #include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 typedef int Status; typedef struct Node { int data; int count; struct Node *llink,*rlink; }Node,*Tree; Status SearchBST(Tree T,int key,Tree *p); Status InsertBST(Tree *T,int e); void Back_reverse_print1(Tree T,int x); void Back_reverse_print1(Tree T,int x); int main() { Tree T; T=(Tree)malloc(sizeof(Node)); T=NULL; int e; printf("What number you want to search--0 to quit:"); scanf("%d",&e); while(e) { if(!InsertBST(&T,e)) printf("Done!"); else printf("It`s been inserted for the first time."); printf("\nWhat number you want to search--0 to quit:"); scanf("%d",&e); } int x; printf("打印大于x的数:"); scanf("%d",&x); while(x) { Back_reverse_print1(T,x); printf("\n"); Back_reverse_print2(T,x); printf("打印大于x的数:"); scanf("%d",&x); } printf("\n"); return 0; } Status SearchBST(Tree T,int key,Tree *p) { if(!T) { *p=T; return FALSE; } else { while(T) { if(key==T->data) { *p=T; T->count++; return TRUE; } else if(key<T->data) { *p=T; T=T->llink; } else { *p=T; T=T->rlink; } } return FALSE; } } Status InsertBST(Tree *T,int e) { Tree p; p=(Tree)malloc(sizeof(Node)); if(!SearchBST(*T,e,&p)) { Tree s; s=(Tree)malloc(sizeof(Node)); s->data=e; s->llink=s->rlink=NULL; s->count=0; if(!p) (*T)=s; else if(e<p->data) p->llink=s; else p->rlink=s; return TRUE; } else { printf("It`s been searched for %d times.",p->count); return FALSE; } } //非递归版本 void Back_reverse_print1(Tree T,int x) { Tree S[20]; int top=0; while(T ||top>0) { while(T) { if(T->data>x) { S[++top]=T; T=T->llink; } else T=T->rlink; } if(top>0) { T=S[top--]; printf("%d ",T->data); T=T->rlink; } } } //递归版本 void Back_reverse_print2(Tree T,int x) { if(T) { if(T->data>x) { Back_reverse_print2(T->llink,x); printf("%d ",T->data); } Back_reverse_print2(T->rlink,x); } }
    最新回复(0)