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


    #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);
    }
    

  • 相关阅读:
    TThread.CreateAnonymousThread 多线程
    flask——包含,继承,宏
    flask-数据库
    flask框架--模板
    flask框架--cookie,session
    flask框架~简易编写
    flask框架1
    第2题:设计包含min函数的栈
    第1题:把二叉搜索树转换为一个排序的双向链表
    关于过渡机制一点理解
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/12699672.html
Copyright © 2020-2023  润新知