二叉树
1.求解二叉树的第K层结点问题:
//输出第k层的结点
void Print_K(struct BtNode* p,int k)
{
if(p!=NULL && k==0)
{
cout<<p->val<<" ";
}
else if(p!=NULL)
{
Print_K(p->leftchild,k-1);
Print_K(p->rightchild,k-1);
}
}
void Print_K_Level(struct BtNode *p,int k)
{
if(p==NULL || k<0)
{
return;
}
Print_K(p,k);
cout<<endl;
}
2.求解二叉树的深度
//求解二叉树的深度
int GetDepth(struct BtNode* p)
{
//左树与右树比较 那个大 +1
if(p==NULL) return 0;
else return max(GetDepth(p->leftchild),GetDepth(p->rightchild))+1;
}
3.求解二叉树的结点个数
//求解二叉树的结点
int GetSize(struct BtNode* p)
{
//左孩子+右孩子+1;
if(p==NULL) return 0;
else return GetSize(p->leftchild)+GetSize(p->rightchild)+1;
}
4.查询二叉树的某个值,存在返回地址,不存在返回NULL
//查询二叉树的值,有则返回地址,无则返回NULL
struct BtNode* FindVal(struct BtNode* p,char target)
{
if(p!=NULL && p->val==target)
{
return p;
}
else
{
struct BtNode* ptr=FindVal(p->leftchild,target);
if(ptr==NULL)
{
ptr=FindVal(p->rightchild,target);
}
return ptr;
}
return NULL;
}
5.找寻二叉树的某个点的双亲结点
struct BtNode *Parent(struct BtNode* ptr,struct BtNode* child)
{
if(ptr==NULL || ptr->leftchild==child || ptr->rightchild==child)
{
return ptr;
}
else
{
struct BtNode* p=Parent(p->leftchild,child);
if(p->leftchild==NULL)
{
p=Parent(p->rightchild,child);
}
return p;
}
}
struct BtNode* FindParent(struct BtNode* ptr,struct BtNode* child)
{
if(ptr==NULL || child==NULL || ptr==child)
{
return NULL;
}
else
{
return Parent(ptr,child);
}
}
6.判断是否是满二叉树
//判断是否是满二叉树
int Is_Full_Tree(struct BtNode *ptr)
{
//深度计算结点
if(ptr==NULL || (Is_Full_Tree(ptr->leftchild) && Is_Full_Tree(ptr->rightchild) && GetDepth(ptr->leftchild)==GetDepth(ptr->rightchild)))
{
return 1;//1为true 0为false
}
return 0;
}
7.判断是否为完全二叉树
//判断是否为完全二叉树
bool Is_Comp_BinTree(struct BtNode *ptr)
{
bool res=true;
if(ptr==NULL) return res;
queue<struct BtNode *>qu;
qu.push(ptr);
while(!qu.empty())
{
ptr=qu.front();
qu.pop();
if(ptr->data==NULL)
{
break;
}
qu.push(ptr->leftchild);
qu.push(ptr->rightchild);
}
while(!qu.empty())
{
ptr=qu.front();
qu.pop();
if(ptr!=NULL)
{
res=false;
break;
}
}
return res;
}