• 建立二叉树(二叉链表存储)


    #include<stdio.h>
    #include<stdlib.h>
    
    //二叉链表
    //typedef struct BitLink {
    //	int data;
    //	struct BitLink* leftChild; //左指针
    //	struct BitLink* rightChild; //右指针
    //}bitlink;
    
    //用二叉链表存储方式建树
    typedef struct BitTree {
    	int data;
    	struct BitTree* LChild; //左子树
    	struct BitTree* RChild; //右子树
    }bittree;
    
    bittree* createBitTree(bittree* BT) {
    	BT = (bittree*)malloc(sizeof(bittree));
    	BT->data = 1;
    	BT->LChild = (bittree*)malloc(sizeof(bittree));
    	BT->RChild = (bittree*)malloc(sizeof(bittree));
    	BT->LChild->data = 2;
    	BT->LChild->RChild = NULL;
    	BT->RChild->data = 3;
    	BT->RChild->LChild = NULL;
    	BT->RChild->RChild = NULL;
    	BT->LChild->LChild = (bittree*)malloc(sizeof(bittree));
    	BT->LChild->LChild->data = 4;
    	BT->LChild->LChild->LChild= NULL;
    	BT->LChild->LChild->RChild = NULL;
    	return BT;
    }
    void main() {
    	bittree* myBT = NULL;
    	myBT = createBitTree(myBT);
    	printf("树的根节点是:%d
    ", myBT->data);
    	printf("树的叶子节点是:%d,%d
    ", myBT->LChild->LChild->data, myBT->RChild->data);
    }
    

     使用递归的方式建立:

    #include<stdio.h>
    #include<stdlib.h>
    
    //用二叉链表存储方式建树(完全二叉树)
    typedef struct BitTree {
    	int data;
    	struct BitTree* LChild; //左子树
    	struct BitTree* RChild; //右子树
    }bittree;
    
    //创建二叉树
    bittree* createBitTree(bittree* BT) {
    	int num = 0;
    	scanf("%d", &num);
    	if (num != -1) {  //输入-1代表结束
    		BT = (bittree*)malloc(sizeof(bittree));
    		BT->data = num;
    		printf("输入%d的左结点值:", BT->data);
    		BT->LChild=createBitTree(BT->LChild);
    		printf("输入%d的右结点值:", BT->data);
    		BT->RChild=createBitTree(BT->RChild);
    		return BT;
    	}
    }
    
    
    void main() {
    	bittree* myBT = NULL;
    	myBT=createBitTree(myBT);
    	printf("树的根结点是:%d
    ", myBT->data);
    	printf("树的根结点的左结点是:%d
    ", myBT->LChild->data);
    	printf("树的根结点的右结点是:%d
    ", myBT->RChild->data);
    }
    

  • 相关阅读:
    JVisualVM简介与内存泄漏实战分析
    高并发性能提升和超卖的解决方案
    ehcache应用场景及集群同步(RMI)
    一台机器配置多个tomcat的实践经验
    事务范围数据库读写分离失败
    基于spring的数据库读写分离
    Zookeeper linux下使用
    Zookeeper集群
    Dubbo入门实例(二)
    Zookeeper安装与启动
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/12699672.html
Copyright © 2020-2023  润新知