被二叉树折磨的死去活来,这里是二叉树的建立,从书上摘抄代码并注上注释,留下来方便以后学习吧,加油阿菜T-T.
从文本文件读入一组整数,用一颗二叉树存储着些整数,读入的第一个整数存储在根结点root上,以后每读一个整数时,向root代表的二叉树上插入一个新的结点,存储所读入的整数,在最终的二叉树上,任取一个结点A:A的值不小于它左子树上任何的值,它右子树上每个值都大于A的值。附上代码:
#include<stdio.h>
#include<stdlib.h>
struct TreeNode{//二叉树节点的数据类型 ,
//数据域 ,数据域定义了要存储的数据元素的类型
int val;
//指针域 ,定义两个指针 ,左指针和右指针,它们的类型必须与二叉树结点的数据类型一致
TreeNode*left,*right;
};
TreeNode * insertTree(TreeNode * root,int val){//向二叉树中添加新的结点 ,此处定义了一个递归函数,向二叉树中添加新的结点
TreeNode * newNode;
if(root==NULL){//如果root所指向的二叉树为空,则将新结点作为二叉树的根节点
newNode=new TreeNode;//每次添加一个结点,存储元素值val
newNode->val=val;
newNode->left=NULL;
newNode->right=NULL;
return(newNode);
}
if(val<=root->val)//如果val小于或等于root的值,将新结点插入到root结点的左子树上
root->left=insertTree(root->left,val);
else//如果val大于root结点的值,将新结点插在root结点的右子树上。
root->right=insertTree(root->right,val);
return(root);
}
void delTree(TreeNode * root){//此处定义一个递归函数,删除root所指向的二叉树的形状 ,释放各个节点所占用的存储空间
if(root->left!=NULL) delTree(root->left);//删除左子树
if(root->right!=NULL) delTree(root->right);//删除右子树
delete root;//删除根结点
return;
}
void printTree(TreeNode * root,char offset[]){//此处定义一个递归函数,用来查看root所指向的二叉树的形状。
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);
return;
}
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;
}
运行结果: