复习数据结构,建树和树的三种遍历
二叉排序树的查询,插入
二叉排序树插入一个节点,此节点一定是叶子节点
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<cstdlib> #include<cmath> #include<vector> #include<queue> #include<map> #include<set> using namespace std; typedef long long ll; typedef struct Node { int key; struct Node *lt,*rt; }Tree; int a[105],d,b[105],d1,c[105],d2; Tree *q; Tree* search_t(Tree* p,int key) { Tree *now; q = now = p; while(now) { if(now->key==key) return now; else if(now->key < key) { q = now; now = now->rt; } else { q = now; now = now->lt; } } return NULL; } void insert_t(Tree* p,int key) { Tree *t; t = (Tree*)malloc(sizeof(Tree)); t->key = key; t->lt = t->rt = NULL; if(p==NULL) p = t; else if(p->key>key) p->lt=t; else p->rt=t; } void LTR(Tree *q) { Tree *pp=q; if(pp==NULL) return; if(pp->lt) LTR(pp->lt); a[d++] = pp->key; if(pp->rt) LTR(pp->rt); } void TLR(Tree *q) { Tree *pp=q; if(pp==NULL) return; b[d1++] = pp->key; if(pp->lt) TLR(pp->lt); if(pp->rt) TLR(pp->rt); } void LRT(Tree *q) { Tree *pp=q; if(pp==NULL) return; if(pp->lt) LRT(pp->lt); if(pp->rt) LRT(pp->rt); c[d2++] = pp->key; } int main() { int n,x; while(~scanf("%d",&n)) { memset(a,0,sizeof(a)); memset(b,0,sizeof(a)); memset(c,0,sizeof(a)); Tree *r; scanf("%d",&x); r = (Tree*)malloc(sizeof(Tree)); r->key = x; r->lt =r->rt = NULL; for(int i=1;i<n;i++) { scanf("%d",&x); if(!search_t(r,x)) insert_t(q,x); } d = d1=d2=0; TLR(r); LTR(r); LRT(r); for(int i=0;i<d1;i++) printf("%d ",b[i]); printf("\n"); for(int i=0;i<d;i++) printf("%d ",a[i]); printf("\n"); for(int i=0;i<d2;i++) printf("%d ",c[i]); printf("\n"); } return 0; }
时间: 2024-11-05 23:37:08