二叉树创建

1.结点添加的简单方式

#include <stdio.h>
#include<stdlib.h>
typedef struct node
{

	int value;
	struct node *pLeft;
	struct node *pRight;

}BinaryTree;
BinaryTree *CreateTree()
{
	BinaryTree *pRoot = NULL;
	pRoot = (BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->value =1;
	pRoot->pLeft =NULL;
	pRoot->pRight=NULL;
	//根的左
	pRoot->pLeft= (BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->pLeft->value = 2;
	pRoot->pLeft->pLeft=NULL;
	pRoot->pLeft->pRight =NULL;

	//左的左
	
	pRoot->pLeft->pLeft =(BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->pLeft->pLeft->value =4;
	pRoot->pLeft->pLeft->pLeft = NULL;
	pRoot->pLeft->pLeft->pRight =NULL;

	//左的右
	pRoot->pLeft->pRight =(BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->pLeft->pRight->value =5;
	pRoot->pLeft->pRight->pLeft =NULL;
	pRoot->pLeft->pRight->pRight =NULL;
	
	//根的右
	pRoot->pRight= (BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->pRight->value =3;
	pRoot->pRight->pLeft=NULL;
	pRoot->pRight->pRight =NULL;
	//右的左
	

	pRoot->pRight->pLeft =(BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->pRight->pLeft->value =6;
	pRoot->pRight->pLeft->pLeft= NULL;
	pRoot->pRight->pLeft->pRight =NULL;
	return pRoot;

}

2.通过传入数组的方式

利用完全二叉树的性质,二叉树的结点值等于传入数组的值,根结点编号为0,编号为i的结点,当2*i+1<=n-1;该结点存在左孩子,当2*i+2<=n-1;该结点存在右孩子

BinaryTree *ArrTree(int arr[],int length)
{
	BinaryTree *p = NULL;
	p=(BinaryTree*)malloc(sizeof(BinaryTree)*length);
	for(int i=0;i<length;i++)
	{
		p[i].value = arr[i];
		p[i].pLeft = NULL;
		p[i].pRight =NULL;

	}
	for(int i=0;i<=length/2-1;i++)
	{
		if(2*i+1<=length-1)
			p[i].pLeft =&p[2*i+1];
		if(2*i+2<=length-1)
			p[i].pRight=&p[2*i+2];
	}
	return p;


}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值