树的算法题学习
//1.计算度为2 度为1 度为0的结点个数
void Count(BiTree bt)
{
if(bt)
{
if(bt->lchild && bt->rchild) n2++;
else if(bt->lchild && !bt->rchild || bt->rchild && !bt->lchild)
n1++;
else n0++;
if(bt->lchild != nullptr) Count(bt->lchild);
if(bt->rchild != nullptr) Count(bt->rchild);
}
}
//2.计算叶子节点个数
int BinaryTreeLeavesCount(BiTree root, int &count) {
if (root != NULL && root->lchild == NULL && root->rchild == NULL) {
count++;
}
if (root!=NULL) {
BinaryTreeLeavesCount(root->lchild, count);
BinaryTreeLeavesCount(root->rchild, count);
}
return count;
}
//3、东北大学2014年查找值为X的结点 返回结点在树中的层数
int search(BiTree t,int x,int count)
{
BiTree p;
p = t;
if(p == nullptr)
return 0;
if(x == p->data)
{
return count;
}else
{
int l = search(p->lchild,x,count+1);
if(l != 0)
return l;
else
return search(p->rchild,x,count+1);
}
}
//4、查找小于等于X结点的个数
int count_search(BiTree t,int x)
{
if(!t) return 0;
if(t->data <= x)
{
return count_search(t->lchild,x)+count_search(t->rchild,x)+1;
}
else
return count_search(t->lchild,x)+count_search(t->rchild,x);
}
//5、输出平衡二叉树的节点
bool isBalanced(BiTree root)
{
int s = Treeheight(root->lchild) - Treeheight(root->rchild);
if(s==0 || s==-1 || s==1)
{
return true;
}
return false;
}
void pingheng(BiTree root)
{
if(root!=nullptr)
{
if(isBalanced(root))
{
cout<<root->data<<" ";
}
pingheng(root->lchild);
pingheng(root->rchild);
}
}
保持好奇心!