//二叉树的建立
#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\n",offset,root->val);
sprintf(str,"%s%s",offset," ");
if(root->left!=NULL)
printTree(root->left,str);
else
printf("%s$\n",str);
if(root->right!=NULL)
printTree(root->right,str);
else
printf("%s$\n",str);
}
int main()
{
FILE *fin;
TreeNode *root;
int val;
char str[81],inFile[30];
printf("input the data file's name\n");
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;
}
二叉树的建立
最新推荐文章于 2020-12-12 20:25:07 发布