有关二叉树简单的操作

补充:

补充遍历方法中的层序遍历:
思路:使用队列的思想进行实现

1、队列Q初始化。

2、如果二叉树非空,将根指针入队

3、循环直到队列为空

      3.1q=队列队头元素出队;

      3.2访问节点的数据域。

      3.3若节点的左儿子存在,则左儿子的指针入队

      3.3若节点的右儿子存在,则右儿子的指针入队

下面是具体的代码实现

struct BiNode
{
	DataType data;
	BiNode<DataType> *lchild,*rchild;
}//节点的定义
//
//以下省略了BiTree的定义,在之前的代码中已经写过了,不再赘述了
//
template<class DataTypa>
void BiTree<DataType>::LevelOrder(BiNode<DataType> *root)
{
	queue <BiNode<DataType> *> q;//注意入队的元素是什么类型的,本题中入队的显然是指针,所以在实例化queue时要是用BiNode类型
	if(root)
      q.push(root);
	while(!q.empty()){
		root=q.front();
        q.pop();
		cout<<root->data<<endl;
        if(root->lchild)
		{
			q.push(root->lchild);
		}
		if(root->rchild)
		{
			q.push(root->rchild);
		}
	}
}

因为编译器崩了,没有来的急进行测试,但是基本八九不离十,没有用复杂的递归方法,所以出错的概率应该不是很大。

二叉树简单统计

1、统计节点的个数

方法有两种:
(1)是采用前序遍历的思想,一遍遍历,一年统计数目,也是最简单的

void count(BiNode<DataType> *root){
      if(root==NULL)
        return;
      if(root){
        count(root->lchild);
        number++;//在之前定义过的计数器
        count(root->rchild);
}

(2)采用的是一个性质:一个树上节点的个数等于左右子树上节点个数+1

template <class DataType>
//因为要使用递归来实现计数器的加减,并且要不断的当做返回值来被获取,所以在这要被定义成int类型
int BiTree<Dataype>::count(BiNode<DataType *root>)
{
	int number=0;
	if(root==NULL)
		number=0;
	else
		number=count(root->lchild)+count(root->rchild)+1;
	return number;

}
//其实想想还是前序遍历实现计数比较的简单

2、统计叶子节点的个数

(1)在前序遍历中实现,定义一个专门用来统计叶子结点个数的计数器,判断一个节点是不是一个叶子结点,如果是的话,计数器加一,不是的话继续放分自己的左右子树。

template <class DataType>
void BiTree<DataType>::leafcount(BiNode<DataType> *root)
{
	if(root)
	
	{
		if(root->lchild==NULL&&rroot->rchild==NULL)
	{
		count++;//已经定义,表示的是叶子节点计数器
	}
	else
	{
		leafcount(root->lchild);
		leafcount(root->rchild);
	}
	}
	return;
}
//遍历真香

遍历的思想比较简单,而且容易理解。

(2)采用性质:一个树的叶子节点的个数等于左右子树叶子节点个数之和。

template <class DataType>
//因为要返回整型的值,所以要定义为int类型为返回类型
int BiTree<DataType>::leafcount(BiNode<DataType> *root)
{
	int number=0;
	if(root==NULL)
		number=0;
	if(root->lchild==NULL&&root->rchild==NULL)
		number=1;
	else
		number=leafcount(root->lchild)+leafcount(root->rchild);
	return number;
}

还是比较菜,遍历真香。

3、求树的高度

(1)其实还是可以利用遍历来做,就是找父节点和子节点之间的关系,左儿子是父亲的两倍,右儿子是父亲节点的两倍+1,可以通过这个性质找到,儿子所在的层数,从而确定树的高度。

(2)还是利用左右子树进行统计,寻找到最长的子树,在子树高度的基础上+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;
}

还有一些其他的方法,因为实验课时间有限,,等回去结合相关题目在写一点吧,最近一直在看深度学习的内容,后面也会写一点关于深度学习的内容。

总结一句吧,遍历一定要注意结束条件!!

发布了47 篇原创文章 · 获赞 6 · 访问量 5214

猜你喜欢

转载自blog.csdn.net/qq_41705207/article/details/89465193