类似归并排序的思想。先求最底层结点的高度,再分别比较生成更高的结点的高度。最后递归至根结点,求出根结点的高度。
//求二叉树的高度
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-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 += 1;
if (k > 1)
{
if (root->_leftchild != nullptr)
count += count_Node(root->_leftchild, k - 1);
if (root->_rightchild != nullptr)
count += count_Node(root->_rightchild, k - 1);
}
return count;
}最近的祖先结点:即可以到达两个结点,并且离两个结点最近的那个结点。可以编写一个判断结点是否存在二叉树的find函数,从而通过从根结点开始遍历其左右子树,一直到无法同时走到那两个结点的结点位置(递归最深的那次),则上一个结点即为最近的祖先结点。
//求最近公共祖先结点
Node<T>* findancestor(T x1, T x2)
{
return findancestor(_root, x1, x2);
}
Node<T>* findancestor(Node<T> *root, T x1, T x2)
{
if (root == nullptr)
return nullptr;
if (findNode(root, x1) && findNode(root, x2))
{
if (findancestor(root->_leftchild, x1, x2) != nullptr)
root = root->_leftchild;
if (findancestor(root->_rightchild, x1, x2) != nullptr)
root = root->_rightchild;
return root;
}
return nullptr;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
求二叉树的高度,叶子节点个数,第K层结点个数,求祖先结点问题
原文地址:http://blog.csdn.net/u011805719/article/details/46919277