• 二叉树的建立


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

  • 相关阅读:
    Eclipse
    svn 常用
    spidermonkey编译
    float format 显示
    点击6次修改服务器地址
    UITextField字数限制
    UINavigationController
    运行时runtime
    IOS 技术与面试
    Cocos2dx笔记
  • 原文地址:https://www.cnblogs.com/javafly/p/6037167.html
Copyright © 2020-2023  润新知