//二叉树的建立 #include<stdio.h> #include<stdlib.h> struct TreeNode{ int val; TreeNode *left,*right; }; TreeNode *insertTree(TreeNode *root,int val){ TreeNode *newNode; if(root==NULL){ newNode=new TreeNode; newNode->val=val; newNode->left=NULL; newNode->right=NULL; return newNode; } if(val<=root->val) root->left=insertTree(root->left,val); else root->right=insertTree(root->right,val); return root; } void delTree(TreeNode *root){ if(root->left!=NULL) delTree(root->left); if(root->right!=NULL) delTree(root->right); delete root; } void printTree(TreeNode *root,char offset[]){ char str[81]; printf("%s%d ",offset,root->val); sprintf(str,"%s%s",offset," "); if(root->left!=NULL) printTree(root->left,str); else printf("%s$ ",str); if(root->right!=NULL) printTree(root->right,str); else printf("%s$ ",str); } int main() { FILE *fin; TreeNode *root; int val; char str[81],inFile[30]; printf("input the data file's name "); scanf("%s",inFile); fin=fopen(inFile,"r"); root=NULL; while(fscanf(fin,"%d",&val)!=EOF) root=insertTree(root,val); fclose(fin); sprintf(str,"%s",""); printTree(root,str); delTree(root); return 0; }