//ptr是记录每层的节点数的数组,i是指树的某一层
if (str != NULL)
{
//每次递归都将该层的节点数加到相应的数组中去
ptr[i]++;
CountLine(str->leftChild, ptr, i + 1);
CountLine(str->rightChild, ptr, i + 1);
}
}
template<typename T>
int BinaryTree<T>::FindMaxLine()
{
//开辟相应的数组来存储每层的节点数
int height = Height();
int* str = new int[height];
for (int i = 0; i < height; i++)
str[i] = 0;
//获得节点数
CountLine(this->root, str, 0);
int max = 0;
//对数组进行处理,获得最大值
for (int i = 0; i < height; i++)
{
if (max < str[i])
max = str[i];
}
return max;
}
template<typename T>
int BinaryTree<T>::CountLine()
{
//利用非递归的方法求出每层的节点数
BinaryTreeNode<T>* str = this->root;
if (str == NULL)
return 0;
queue<BinaryTreeNode<T>*>node;
node.push(str);
int max = 0;
while (!node.empty())
{
int cur = 0;
int curSize = node.size();
while (cur < curSize)
{
cur++;
str = node.front();
node.pop();
if (str->leftChild)
node.push(str->leftChild);
if (str->rightChild)
node.push(str->rightChild);
}
if (max < curSize)
max = curSize;
}
return max;
}