6.8 树习题

各种遍历二叉树的实际应用

  • 6.42 求以二叉链表为存储结构的二叉树中叶子结点的个数
int i = 0;
Status LeafNodeNum(int &i, BiTree &T)
{
	// i的值可以在被调用的地方改变
	if(T)
	{
		if(!T->lchild && !T->rchild)
		{
			i++;
		}
		LeafNodeNum(i, T->lchild);
		LeafNodeNum(i, T->rchild);
	}
	return OK;
}
  • 6.43 二叉链表 按先序交换二叉树的左右子树
Status ExchangeBiTree(BiTree &T)
{
	BiTree p;
	if(T)
	{
		p = T->lchild;
		T->lchild = T->rchild;
		T->rchild = p;
		ExchangeBiTree(T->lchild);
		ExchangeBiTree(T->rchild);
	}
	return OK;
}
  • 6.46 复制一棵二叉树 (二叉链表结构)
typedef struct BiTNode
{
	TElemType data;
	struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree

Status CopyBiTree(BiTree &T, BiTree &T1)
{
	BiTree p;
	if(T)
	{
		p = (BiTree)malloc(sizeof(BiTMode));
		if(!p)
		{
			return ERROR;
		}
		p->data = T->data;
		T1 = p;
		CopyBiTree(T->lchild, T1->lchild);
		CopyBiTree(T->rchild, T1->rchild);
	}
	else
	{
		T1 = T;
	}
	return OK;
}
  • 6.47 按层次顺序(同一层从左向右)遍历二叉树的算法
Status LevelOrderTraverse(BiTree &T, Status (*visit)(TElemType e))
{
	QElemType p; // p用来存储树中结点
	Queue q; // 存放结点的队列
	InitQueue(q);

	if(T)
	{
		EnQueue(q, T);
		while(!QueueEmpty(q))
		{
			DeQueue(q, p);
			visit(p->data);
			if(p->lchild)
			{
				EnQueue(q, p->lchild);
			}
			if(p->rchild)
			{
				EnQueue(Q, p->rchild);
			}
		}
	}
	return OK;
}
  • 6.49 判断一棵二叉树是否是完全二叉树 (二叉链表)
Status CompleteBiTree(BiTree &T)
{
	int d;
	if(T)
	{
		d = BiTDepth(T->lchild) - BiTDepth(T->rchild);
		if(d<0 || d > 1)
		{
			return ERROR;
		}
		else
		{
			if(CompleteBiTree(T->lchild) 
					&& CompleteBiTree(T->rchild) )
			{
				return OK;
			}
			else
			{
				return ERROR;
			}
		}
	}
	return OK;
}
  • 6.60 对以孩子-兄弟二叉链表为存储结构的树求叶子结点的个数
    (重点就是确认自己需要二叉链表中什么特点的结点,比如找树的叶子结点,那么在二叉链表中反应的就是firstchild域为空的结点)
int LeafNum(CSTree &T)
{
	if(T)
	{
		if(!T->firstchild)
		{
			return 1+LeafNum(T->nextsibling);
		}
		else
		{
			return LeafNum(T->firstchild)+LeafNum(T->nextsibling);
		}
	}
	else
	{
		return 0;
	}
}
  • 6.61 对 以孩子-兄弟二叉链表结构 表示的树 求树的度
typedef struct CSNode
{
	ElemType data;
	struct CSNode *firstChild, *nextSibling;
} CSNode, *CSTree;

int DegreeNum(CSTree &T)
{
	// d 存放现结点的度,dl 存放现结点的第一个子结点的度
	// dr 存放现结点的第二个子结点的度
	int d, dl, dr;
	if(T)
	{
		if(!T->firstchild)
		{
			d = 0;
		}
		else
		{
			// 1 + 第一个子结点的兄弟结点的个数
			d = 1 + RSiblingNum(T->firstchild);
		}
		dl = DegreeNum(T->firstchild);
		dr = DegreeNum(T->nextsibling);
		return Max(d, dl, dr);
	}
	else
	{
		return 0;
	}
}

// 返回当前结点的兄弟数
int RSiblingNum(CSTree &T)
{
	int i = 0;
	while(T->nextsibling)
	{
		i++;
		T = T->nextsibling;
	}
	return i;
}
  • 6.62 对 以孩子-兄弟链表结构 表示的树编写计算深度的方法
int Depth(CSTree &T)
{
	int d1, d2;
	if(T)
	{
		d1 = 1 + Depth(T->firstchild);
		d2 = Depth(T->nextsibling);
		return d1>d2?d1:d2;
	}
	else
	{
		return 0;
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值