数据结构-二叉树的操作实现学习

二叉树的操作实现
(1),节点结构体定义:

typedef struct Node{
	DataType data;			//数值域
	struct Node *leftChild;	//左子树指针
	struct Node *rightChild;	//右子树指针
}BiTreeNode;

(2),初始化

void Initiate(BiTreeNode **root)
{
	*root = (BiTreeNode *)malloc(sizeof(BiTreeNode));
	(*root)->leftChild = NULL;
	(*root)->rightChild = NULL;
}

(3),左插入节点
//若当前节点curr非空,则在curr的左子树插入元素值为x的新节点
//原curr所指结点的左子树成为新插入的节点的左子树
//若插入成功,则返回新插入节点的指针,否则返回空指针

BiTreeNode *InsertLeftNode(BiTreeNode *curr, DataType x)
{
	BiTreeNode *s, *t;
	
	if(curr == NULL)
	{
		return NULL;
	}
	
	t = curr->leftChild;		//保留原curr所指结点的左子树指针
	s = (BiTreeNode *)malloc(sizeof(BiTreeNode));
	s->data = x;
	s->leftChild = t;		//新插入节点的左子树为原curr的左子树
	s->rightChild = NULL;
	
	curr->leftChild = s;	//新节点成为curr的左子树。
	
	return curr->leftChild;	//返回新插入节点的地址
}

(4),右插入节点
//若当前节点curr非空,则在curr的右子树插入元素值为x的新节点
//原curr所指结点的右子树成为新插入的节点的右子树
//若插入成功,则返回新插入节点的指针,否则返回空指针

BiTreeNode *InsertRightNode(BiTreeNode *curr, DataType x)
{
	BiTreeNode *s, *t;
	
	if(curr == NULL)
	{
		return NULL;
	}
	
	t = curr->rightChild;		//保留原curr所指结点的左子树指针
	s = (BiTreeNode *)malloc(sizeof(BiTreeNode));
	s->data = x;
	s->rightChild = t;		//新插入节点的左子树为原curr的左子树
	s->leftChild = NULL;
	
	curr->rightChild = s;	//新节点成为curr的左子树。
	
	return curr->rightChild;	//返回新插入节点的地址
}

(5),左删除节点
//若curr非空,则删除curr所指结点的左子树
//若删除成功,则返回删除节点的双亲结点指针, 否则返回空指针。

BiTreeNode *DeleteLeftNode(BiTreeNode *curr)
{
	if((curr == NULL) || (curr>leftChild == NULL))
	{
		return NULL;
	}
	
	Destroy(&curr->leftChild);
	curr->leftChild = NULL;
	
	return curr;
}

(6),右删除节点
//若curr非空,则删除curr所指结点的右子树
//若删除成功,则返回删除节点的双亲结点指针, 否则返回空指针。

BiTreeNode *DeleteLeftNode(BiTreeNode *curr)
{
	if((curr == NULL) || (curr>rightChild == NULL))
	{
		return NULL;
	}
	
	Destroy(&curr->rightChild);
	curr->rightChild = NULL;
	
	return curr;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值