- 实现森林先根(已提供)、后根遍历递归算法;
- 计算森林的叶子节点个数(递归算法);
- 计算森林的高度(递归算法);
代码示例👇
//author:Mitchell_Donovan
//date:4.20
#include<iostream>
using namespace std;
template<class T>
class TreeNode {
//添加友元类声明,便于森林类Tree对其进行一系列访问与修改
template<class T>
friend class Tree;
private:
T data;
TreeNode<T>* child;
TreeNode<T>* brother;
public:
//无参数的构造函数
TreeNode() :data(T()), child(NULL), brother(NULL) {}
//有参数的构造函数
TreeNode(T value) :data(value), child(NULL), brother(NULL) {}
//析构函数
virtual~TreeNode() {
child = NULL;
brother = NULL;
}
//判断当前结点是否为叶结点
bool isLeaf() {
if (child == NULL) {
return true;
}
else {
return false;
}
}
//返回结点的值
T getValue() {
return data;
}
//返回左子结点
TreeNode<T>* getChild() {
return child;
}
//返回右兄弟结点
TreeNode<T>* getBrother() {
return brother;
}
//设置当前结点的值
void setValue(const T& value) {
data = value;
}
//设置左子结点
void setChild(TreeNode<T>* pointer) {
child = pointer;
}
//设置右兄弟结点
void setBrother(TreeNode<T>* pointer) {
brother = pointer;
}
};
template<class T>
class Tree {
private:
TreeNode<T>* root;
public:
//构造函数
Tree() {
root = NULL;
cout << "Now start to construct the tree! " << endl;
cout << "Please enter a value or '#' to stop:";
createTree(root);
}
//析构函数
virtual~Tree() {
root = NULL;
}
//先序构造森林
void createTree(TreeNode<T>*& node) {
T value;
cin >> value;
if (value == '#') {
node = NULL;
}
else {
node = new TreeNode<T>(value);
createTree(node->child);
createTree(node->brother);
}
}
//取根结点
TreeNode<T>* getRoot() {
return root;
}
//先根深度优先周游树
void rootFirst(TreeNode<T>* node) {
while (node != NULL) {
cout << node->data << " ";
rootFirst(node->child);
node = node->brother;
}
}
//后根深度优先周游树
void rootLast(TreeNode<T>* node) {
while (node != NULL) {
rootLast(node->child);
cout << node->data << " ";
node = node->brother;
}
}
//计算叶结点个数
int countLeaf(TreeNode<T>* node) {
int count = 0;
while (node != NULL) {
if (node->isLeaf()) {
count++;
}
count += countLeaf(node->child);
node = node->brother;
}
return count;
}
//计算深度
int countDepth(TreeNode<T>* node) {
if (node == NULL) {
return 0;
}
int depth = 0;
int childdepth = countDepth(node->child);
int brotherdepth = countDepth(node->brother);
depth = childdepth + 1 > brotherdepth ? childdepth + 1 : brotherdepth;
return depth;
}
};
int main() {
//AB#CE#F##D###
Tree<char> test;
cout << "\n先根深度优先周游结果是:";
test.rootFirst(test.getRoot());
cout << "\n后根深度优先周游是:";
test.rootLast(test.getRoot());
cout << "\n叶结点个数是:" << test.countLeaf(test.getRoot());
cout << "\n深度是:" << test.countDepth(test.getRoot());
}
输出样例👇