数据结构-以孩子兄弟链表存储树

树以孩子兄弟链表为存储结构,请设计算法求树的深度,求树的度。

头文件

/*CTNode.h*/
#ifndef _CTNODE_H
#define _CTNODE_H
#include<iostream>
using namespace std;
template <class DataType>
class CTNode{
public:
	DataType data;
	CTNode<DataType>* child;
	CTNode<DataType>* sibling;
    CTNode() 		//无参构造函数,创建空节点
    {
        child = sibling = NULL;
    }
    CTNode(const DataType& e, CTNode<DataType>* firstChild = NULL, CTNode<DataType>* nextSibling = NULL)
    {
        data = e;
        child = firstChild;
        sibling = nextSibling;
    }
};
#endif
/*ChildSiblingTree.h*/
#ifndef _CST_H
#define _CST_H
#pragma once
#include"CTNode.h"
using namespace std;
template <class DataType>
class ChildSiblingTree
{
protected:
	CTNode<DataType>* root;                //根指针
	void Destroy(CTNode<DataType>*& r);	//删除以r为根的二叉树
public:
	ChildSiblingTree() :root(NULL) {}			//构造函数
	ChildSiblingTree(const DataType& e);              //构造函数
	~ChildSiblingTree() { Destroy(root); }             //析构函数
	CTNode<DataType>* GetRoot() { return root; }	//返回根指针
	bool IsEmpty() { return root == NULL ? true : false; }	//判断树是否为空
	CTNode<DataType>* FirstChild(CTNode<DataType>* r) const { return r->child; }  //返回以r为根的树的第一个孩子
	CTNode<DataType>* NextSibling(CTNode<DataType>* r) const { return r->sibling; }  //返回p的兄弟
	int Degree(CTNode<DataType>* r) const;           //求以r为根的树的度
	int Height(CTNode<DataType>* r) const;    //求以r为根的树的深度
};
#endif

函数实现

/*ChildSiblingTree.cpp*/
#include"ChildSiblingTree.h"

template <class DataType>
ChildSiblingTree<DataType>::ChildSiblingTree(const DataType& e)
{
	root = new CTNode<DataType>(e);
}
template <class DataType>
void ChildSiblingTree<DataType>::Destroy(CTNode<DataType>*& r) {
	if (r) {
		Destroy(r->child);
		Destroy(r->sibling);
		delete r;
		r = NULL;
	}
}

template <class DataType>
int ChildSiblingTree<DataType>::Height(CTNode<DataType>* r) const
{
	CTNode<DataType>* p;
	if (r == NULL)
		return 0;
	else
	{
		int maxSubTreeHeight = 0, h;
		for (p = FirstChild(r); p != NULL; p = NextSibling(p))
		{
			h = Height(p);
			maxSubTreeHeight = (maxSubTreeHeight < h) ? h : maxSubTreeHeight;
		}
		return maxSubTreeHeight + 1;
	}
};

template <class DataType>
int ChildSiblingTree<DataType>::Degree(CTNode<DataType>* r) const
{
	CTNode<DataType>* p;
	int d = 0;
	int maxSubTreeDegree = 0;
	for (p = FirstChild(r); p != NULL; p = NextSibling(p))
	{
		d++;
		int subTreeDegree = Degree(p);
		maxSubTreeDegree = (maxSubTreeDegree < subTreeDegree) ? subTreeDegree : maxSubTreeDegree;
	}
	return (d < maxSubTreeDegree) ? maxSubTreeDegree : d;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值