设计算法求二叉树的结点个数。
void Count(BiNode *root)
{
if (root) {
Count(root->lchild);
number+ +; //number为数据成员
Count(root->rchild);
}
}
左子树中节点的数目+右子树中节点的数目+1
template<class T>
int BiTree<T>::count(BiNode<T>* root)
{
int number=0;
if (root==NULL)
number=0;
else
number=count(root->lchild)+count(root->rchild)+1;
return number;
}
统计叶子节点的数目
1增加一个数据成员,leafcount, 初值为0
2.对树进行遍历。 如果一个节点是叶子,则将leafcount+1;
可以在前序、中序或后序的遍历过程中进行计算。
从根节点出发
判断当前节点是否是叶子节点,如果是,则叶子数+1
否则,在左子树中遍历,并统计叶子节点的数目,在右子树中进行遍历,并统计叶子节点的数目。
template<typename T>
void BiTree<T>:: countleaf(BiTreeNode<T> * root){
if (root) {
if (root->lchild==0 && root->rchild==0)
leafcount=leafcount+1;
else
{
countleaf(root->lchild);
countleaf(root->rchild);
}
}
return;
}
左子树中叶子节点的数目+右子树中叶子节点的数目
template<class T>
int BiTree<T>::leafcount(BiNode<T>* root)
{
int number=0;
if (root==NULL)
number=0;
else if(root->lchild==NULL && root->rchild==NULL)
number=1;
else
number=leafcount(root->lchild)+leafcount(root->rchild);
return number;
}
计算树的高度
高度的定义:
max(左子树高度,右子树高度)+1
从根节点出发开始计算,
如果root==NULL, 高度为0;
否则,分别计算左子树的高度;右子树的高度;
返回max(左子树高度,右子树高度)+1
递归的定义:
template<typename T>
int BiTree<T>::cal_height(BiTreeNode<T> * root){
int lheight=0,rheight=0;
if (root==0)
return 0;
lheight = cal_height(root->lchild);
rheight = cal_height(root->rchild);
if (lheight>rheight)
return lheight+1;
else
return rheight+1;
}
输出中缀表达式。并加上相应的括号 (a+(b*(c-d)))-(e/f)
基本思想:
中序遍历:
中序遍历左子树前,输出左括号
中序遍历右子树后,输出右括号
如果遍历叶子节点的左右子树,不输出括号
如果遍历根节点的左右子树,不输出括号(否则,会得到形如(a+b)的表达式)
void BiTree<T>::In_Expression(BiNode<T>* root){
if(root)
{
if(root!=this->root&&root->lchild!=0&&root->rchild!=0)
cout<<"(";
In_Expression(root->lchild);
cout<<root->data;
In_Expression(root->rchild);
if(root!=this->root&&root->lchild!=0&&root->rchild!=0)
cout<<")";
}
}