二叉树简单操作

(一)求二叉树的深度

如果一棵树只有一个结点,那么它的深度为1;
如果根结点只有左子树没有右子树,那么树的深度是左子树的深度加1,加1是加上根节点这一层
如果既有左子树又有右子树,那么树的深度应该是左、右子树中深度较大的值再加1

递归代码

int Depth1(BtNode* ptr)
{
	if(ptr == NULL)
		return 0;
	int nleft = Depth1(ptr->leftchild);
	int nright = Depth1(ptr->rightchild);
	return nleft > nright ? nleft + 1:nright+1;
}

非递归 借用队列实现

1.先将root节点入队

2.在每次数据出队之前计算队内数据的数量size, 用size控制出队次数

3.每一层size之后depth加1

4.最后知道队空,返回depth的值

int Depth2(BtNode* ptr)
{
	if(ptr == NULL)
		return 0;
	if(ptr->leftchild == NULL && ptr->rightchild == NULL)
		return 1;

	queue<BtNode*> qu;
	qu.push(ptr);
	int depth = 0;
	
	while(!qu.empty())
	{
		int size = qu.size();
		depth++;
		for(int i = size;i > 0 ;--i)
		{
			ptr = qu.front();qu.pop();
			if(ptr->leftchild != NULL)
				qu.push(ptr->leftchild);
			if(ptr->rightchild != NULL)
				qu.push(ptr->rightchild);
		}
	}
	return depth;
}

(二)层次遍历二叉树

借助队列实现层次遍历

void NiceLevelOrder(BtNode *ptr)
{
	if(ptr == NULL) return ;
	queue<BtNode*> qu;
	qu.push(ptr);

	while(!qu.empty())
	{
		ptr = qu.front();qu.pop();
		cout<<ptr->key<< " ";
		if(ptr->leftchild != NULL)
		{
			qu.push(ptr->leftchild);
		}
		if(ptr->rightchild != NULL)
		{
			qu.push(ptr->rightchild);
		}
	}
	cout<<endl;
}

借助深度特性循环遍历二叉树

void LevelOrder(BtNode* ptr)
{
	if(ptr == NULL )
		return ;
	int level = Depth1(ptr);
	for(int i = 0 ; i < level;++i)
	{
		Print_K_Level_Item(ptr,i);
	}
	cout<<endl;
}

(三)打印二叉树第K层节点

递归代码

void Print_K_Level_Item(BtNode *ptr,int k)
{
	if(ptr == NULL || k < 0)
		return ;
	if(ptr != NULL && k == 0)
		cout<<ptr->key<<" ";
	else
	{
		Print_K_Level_Item(ptr->leftchild,k-1);
		Print_K_Level_Item(ptr->rightchild,k-1);
	}
}

非递归代码

主要思路图

 

void Print_K_Node(BtNode* ptr,int k)
{
	if(ptr == NULL)
		return ;
	if(ptr != NULL && k == 1)
		cout<<ptr->key<<" ";
	else
	{
		queue<BtNode*> qu;
		qu.push(ptr);
		int depth = 0;
		int len = 0;
		while(!qu.empty())
		{
			int  size = qu.size();
			len = size;
			depth++;
			if(depth == k)
			{
				for(int i = 0 ;i < size ;++i)
				{ 
					ptr = qu.front(); qu.pop();
				    cout<<ptr->key<<" ";
					len--;
				}
				if(len == 0)
					break;
			}
			for(int i = 0 ; i < size ;++i)
			{
				ptr = qu.front();qu.pop();
				if(ptr->leftchild != NULL)
				{
					qu.push(ptr->leftchild);
			    }
				if(ptr->rightchild != NULL)
				{
					qu.push(ptr->rightchild);
				}
			}
			
		}
	}
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值