菜鸟写二叉树的操作集

二叉树的操作集

0.预先准备

typedef int ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode {
	ElementType Data;
	BinTree Left;
	BinTree Right;
};
  1. 遍历树
    1.1先序遍历
void PreorderTraversal(BinTree BT)
{
	if (BT) {
		printf("%d ", BT->Data);
		PreorderTraversal(BT->Left);
		PreorderTraversal(BT->Right);
	}
}

1.2中序遍历

void InorderTraversal(BinTree BT)
{
	if (BT) {
		InorderTraversal(BT->Left);
		printf("%d ", BT->Data);
		InorderTraversal(BT->Right);
	}
}

2.树的查找
2.1查找最大值

Position FindMax(BinTree BST) {
	Position temp;
	if (BST == NULL) return BST;
	for (temp = BST; temp->Right != NULL; temp = temp->Right);
	return temp;
}

2.2查找最小值

Position FindMin(BinTree BST) {
	Position temp;
	if (BST == NULL) return BST;
	for (temp = BST; temp->Left != NULL; temp = temp->Left);
	return temp;
}

2.3查找特殊元素

Position Find(BinTree BST, ElementType X) {
	if (!BST)
		return NULL;
	if (X < BST->Data)
		return Find(BST->Left, X);
	else if (X > BST->Data)
		return Find(BST->Right, X);
	else
		return BST;
}

3.树的插入

BinTree Insert(BinTree BST, ElementType X) {
	if (!BST) {
		BST = (BinTree)malloc(sizeof(struct TNode));
		BST->Data = X;
		BST->Left = BST->Right = NULL;
		return BST;
	}
	if (BST->Data > X) {
		BST->Left = Insert(BST->Left, X);
	}
	else if (BST->Data < X) {
		BST->Right = Insert(BST->Right, X);
	}
	return BST;
}

4.树的删除

BinTree Delete(BinTree BST, ElementType X) {
	if (!BST) {
		printf("Not Found\n");
		return BST;
	}
	if (BST->Data == X) {
		if (BST->Left == NULL && BST->Right == NULL) {
			return NULL;
		}
		else if (BST->Left == NULL) {
			return BST->Right;
		}
		else if (BST->Right == NULL) {
			return BST->Left;
		}
		else {
			BinTree temp;
			temp = FindMin(BST->Right);
			BST->Data = temp->Data;
			BST->Right = Delete(BST->Right, temp->Data);
			return BST;
		}
	}
	else if (BST->Data < X) {
		BST->Right = Delete(BST->Right, X);
	}
	else if (BST->Data > X) {
		BST->Left = Delete(BST->Left, X);
	}
	return BST;
}

这也需要板子?还是太菜了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值