#include <stdio.h> #include <stdlib.h> struct TreeNode { int val; TreeNode *left,*right; }; //左子树的节点小于等于根节点,右子树的节点大于等于根节点 TreeNode* InsertTree(TreeNode *root,int val) { TreeNode *node; if(NULL == root) { node = (TreeNode *)malloc(sizeof(TreeNode)); node->val = val; node->left = NULL; node->right = NULL; return node; } else if(val <= root->val) root->left = InsertTree(root->left,val); else root->right = InsertTree(root->right,val); return root; } void DeleteTree(TreeNode *root) { if(root->left) DeleteTree(root->left); if(root->right) DeleteTree(root->right); free(root); } //层次结构打印二叉树 void PrintfTree(TreeNode *root,char level[]) { printf("%s%d/n",level,root->val); char child_level[81]; sprintf(child_level,"%s%s",level," "); if(root->left) PrintfTree(root->left,child_level); else printf("%s$/n",child_level); if(root->right) PrintfTree(root->right,child_level); else printf("%s$/n",child_level); return; } void main() { FILE *fin; TreeNode *root; int val; char fileName[81],level[81]; printf("input the data file's name:/n"); //scanf的格式,不是连续输入的时候不需要'/n' scanf("%s",fileName); fin = fopen(fileName,"r"); root = NULL; while(fscanf(fin,"%d",&val) != EOF) root = InsertTree(root,val); fclose(fin); sprintf(level,"%s",""); PrintfTree(root,level); DeleteTree(root); system("PAUSE"); return; }