二叉树补充--第k层结点,深度,节点个数,双亲结点,满二叉树,完全二叉树的判断

二叉树

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;
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值