二叉排序树的建立

来源:互联网 发布:linux系统的命令 编辑:程序博客网 时间:2024/06/10 18:23
#include <stdio.h>#include <malloc.h>#include <string.h>int k;typedef struct treeNode{int val;struct treeNode *left,*right;}Node;Node *root;Node *newnode(int v){Node *u=(Node*)malloc(sizeof(Node));if(u != NULL){u->val=v;u->left=u->right=NULL;}return u;}void addnode(Node *r,Node *u){if(r == NULL)return;if(u->val > r->val){addnode(r->right,u);if(r->right==NULL)r->right=u;}else if(u->val < r->val){addnode(r->left,u);if(r->left==NULL)r->left=u;}}void remove_tree(Node* u) {  if(u == NULL) return;  remove_tree(u->left);  remove_tree(u->right);  free(u);}void printTree(Node *head){if(head!=NULL){   printf("%d ",head->val);   printTree(head->left);   printTree(head->right);}}int main(){freopen("D:\\in.txt","r",stdin);int n,v;while(scanf("%d",&n)==1){scanf("%d",&v);remove_tree(root);root=newnode(v);for(int i=1;i<n;i++){scanf("%d",&v);Node *u=newnode(v);addnode(root,u);}printTree(root);printf("\n");}}


测试用例,即文件in.txt的内容为:

5
2 5 1 3 4
3
1 2 3

0 0