二叉树的建立

//二叉树的建立
#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;
}

转载于:https://www.cnblogs.com/javafly/p/6037167.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值