【数据结构】删除以结点值x为根结点的子树

假设二叉树中所有结点值为单个字符且均不相同,采用二叉链存储结构存储。设计一个算法利用DestroyBTee删除并释放二叉树b中以结点值x为根结点的子树。其中DestroyBTree(b)用于删除并释放以b为根结点的二叉树,属于二叉树的基本运算算法,可以直接调用;并用相关数据进行测试。

样例输入
A(B(D,E(G,H)),C(,F(I))) B
样例输出
A(,C(,F(I)))

题解

#include 
using namespace std;
#define MaxSize 100
typedef char ElemType;

typedef struct tnode
{	ElemType data;					
	struct tnode *lchild,*rchild;
} BTNode;
void CreateBTree(BTNode*& bt, char* str)//由括号表示串创建二叉链
{
	BTNode* St[MaxSize], * p = NULL;
	int top = -1, k, j = 0;
	char ch;
	bt = NULL;			//建立的二叉树初始时为空
	ch = str[j];
	while (ch != '\0')	//str未扫描完时循环
	{
		switch (ch)
		{
		case '(':top++; St[top] = p; k = 1; break;//为左孩子结点
		case ')':top--; break;
		case ',':k = 2; break;	//为右孩子结点
		default:p = new BTNode();
			p->data = ch; p->lchild = p->rchild = NULL;
			if (bt == NULL)	//*p为二叉树的根结点
				bt = p;
			else			//已建立二叉树根结点
			{
				switch (k)
				{
				case 1:St[top]->lchild = p; break;
				case 2:St[top]->rchild = p; break;
				}
			}
		}
		j++;
		ch = str[j];
	}
}
void DestroyBTree(BTNode*& bt)		//销毁二叉链
{
	if (bt != NULL)
	{
		DestroyBTree(bt->lchild);
		DestroyBTree(bt->rchild);
		delete bt;
	}
}
// 在此处补充你的代码
void DispBTree(BTNode* bt)
{
	if (bt != NULL)
	{
		cout << bt->data;
		if (bt->lchild != NULL || bt->rchild != NULL)
		{
			cout << "(";
			DispBTree(bt->lchild);
			if (bt->rchild != NULL)
			{
				cout << ",";
			}
			DispBTree(bt->rchild);
			cout << ")";
		}
		else
		{
			//null
		}
	}
}
void DestroygreatTree(BTNode *&bt,char x)
{
	if (bt == NULL)
	{
		return;
	}
	if (bt->data == x)
	{
		DestroyBTree(bt);
		bt=NULL;
	}
	if (bt != NULL)
	{
		DestroygreatTree(bt->lchild, x);
		DestroygreatTree(bt->rchild, x);
	}
}
int main()
{
	char tree[MaxSize];
	char ch;
	cin >> tree;
	cin >> ch;
	BTNode* bt;
	CreateBTree(bt, tree);
	DestroygreatTree(bt, ch);
	DispBTree(bt);
	DestroyBTree(bt);
	return 0;
}

你可能感兴趣的:(数据结构,数据结构,算法,图论)