一、求二叉树的高度
类似归并排序的思想。先求最底层结点的高度,再分别比较左右子树高度生成更高的结点的高度。最后递归至根结点,求出根结点的高度。
//求二叉树的高度
int Height()
{
return GetHeight(_root);
}
int GetHeight(Node<T> *root)
{
int left = 0;
int right = 0;
if (root->_leftchild != NULL)
left += GetHeight(root->_leftchild);
if (root->_rightchild != NULL)
right += GetHeight(root->_rightchild);
return left >= right ? (left + 1) : (right + 1);
}
二、求叶子结点的个数
分别递归左右子树,当最后出现结点左右孩子均为空时,其为叶结点,从而进行加一操作。
//求叶子节点的个数
int count_leaves()
{
return count_leaves(_root);
}
int count_leaves(Node<T> *root)
{
int count = 0;
if (root == nullptr)
return count;
if (root->_leftchild != nullptr)
{
count += count_leaves(root->_leftchild);
}
if (root->_rightchild != nullptr)
{
count += count_leaves(root->_rightchild);
}
if (root->_leftchild == nullptr && root->_rightchild == nullptr)
count += 1;
return count;
}
三、求第K层结点的个数
根据思想,求第k层的结点个数,即第k-1层结点的子结点的个数,而第k-1层结点又可以由第k-2层求出.......
//计算二叉树第K层结点的个数
int count_Node(int k)
{
return count_Node(_root, k);
}
int count_Node(Node<T> *root, int k)
{
int count = 0;
if (k == 1)
if (root != NULL)
return count +=