Given a series of integers, build a binary sorted tree and output the results of preorder, inorder and postorder traversal
#include<stdio.h> #include<string.h> struct Node{ Node *lter; Node * rtre; int w; }buf[50]; int a[30]; int loc,n; Node *create(){ buf [loc] .ltre = buf [loc] .rtre = NULL; return &buf[loc++]; } void pre(Node *t){ printf("%d ",t->w); if(t->ltre!=NULL){ pre(t->lter); } if(t->rtre!=NULL){ pre(t->rtre); } } void mid(Node *t){ if(t->ltre!=NULL){ mid(t->ltre); } printf("%d ",t->w); if(t->rtre!=NULL){ mid(t->rtre); } } void aft(Node *t){ if(t->ltre!=NULL){ aft(t->ltre); } if(t->rtre!=NULL){ aft(t->rtre); } printf("%d ",t->w); } void build(int x,Node *t){ if(x>t->w){ if(t->rtre==NULL){ t->rtre=create();//You need to create it first, you can't assign it directly t->rtre->w=x; return; } build(x,t->rtre); } if(x<t->w){ if(t->ltre==NULL){ t->ltre=create(); t->ltre->w=x; return; } build(x,t->ltre); } } int main(){ while(scanf("%d",&n)!=EOF){ loc = 0; Node *t=create(); scanf("%d",&a[0]); t->w=a[0]; for(int i=1;i<n;i++){ scanf("%d",&a[i]); build(a[i],t);//t itself is a pointer, so the address symbol & is not required } pre(t); printf("\n"); mid(t); printf("\n"); aft(t); printf("\n"); } return 0; }
Idea: The point is how to restore a binary sorting tree. The first integer is the root. If the following integer is less than the integer, it is set as the root of the left subtree, and if it is greater than the integer, it is set as the root of the right subtree; each subsequent integer is compared with the root first, and then decides to go to the left. The subtree still goes to the right subtree, and then compares it with the subtree root until it becomes a leaf node.
Function name | Function | incoming | outgoing |
build() | Restore a binary sorted tree from a sequence of integers | current integer, tree pointer | |
aft() | post-order traversal | tree pointer | |
mid() | Inorder traversal | tree pointer | |
pre() |
preorder traversal
|
tree pointer |