zoukankan      html  css  js  c++  java
  • 建立二叉树(二叉链表存储)

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

  • 相关阅读:
    WinForm换行
    aspx获取页面间传送的值
    Response.BinaryWrite()方法输出二进制图像
    Jquery删除table的行和列
    WinForm DataGridView控件隔行变色
    IE中table的innerHTML无法赋值
    C#为IE添加可信任站点
    静态代码检查
    第三方开源小工具
    查看sql server 服务器内存使用情况
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/12699672.html
Copyright © 2011-2022 走看看