boj67

在世界中心呼唤爱

#include <iostream> using namespace std; struct node { int value; node* left; int left_count; node* right; int right_count; }; node * insert(node * head,node * new_node) { if(head==NULL||new_node==NULL)return NULL; node *p=head; if(p->value>new_node->value) { p->left_count++; if(p->left==NULL)p->left=new_node; else { p=p->left; insert(p,new_node); } } else { p->right_count++; if(p->right==NULL)p->right=new_node; else { p=p->right; insert(p,new_node); } } } int find(node * head,int n) { //if(n==0||head==NULL)return 0; if((n-1)==head->left_count) { return head->value; } else if((n-1)>head->left_count) { find(head->right,n-head->left_count-1); } else { find(head->left,n); } } void release(node * head) { node *p=head; if(p!=NULL) { release(p->left); release(p->right); free(p); p=NULL; } } int main() { int n,op,x; node *head=NULL; while(scanf(“%d”,&n)) { if(n==0)break; scanf(“%d %d”,&op,&x); head=(node *)malloc(sizeof(node)); head->value=x; head->left=NULL; head->left_count=0; head->right=NULL; head->right_count=0; n–; while(n–) { scanf(“%d”,&op); if(op==1) { node *new_node=(node *)malloc(sizeof(node)); scanf(“%d”,&x); new_node->value=x; new_node->left=NULL; new_node->right=NULL; new_node->left_count=0; new_node->right_count=0; insert(head,new_node); } else if(op==2) { int node_count=head->left_count+head->right_count+1; if(node_count%2) printf(“%.1f/n”,(double)find(head,(node_count/2+1))); else printf(“%.1f/n”,((double)find(head,node_count/2)+(double)find(head,node_count/2+1))/2.0); } } release(head); } return 0; }

用了二叉排序树来寻找中位数,其中每个节点 left_count和right_count分别代表左右孩子的个数

点赞