从线索二叉树的建立理解递归以及引用的一些妙处

版权声明: https://blog.csdn.net/lnaruto1234/article/details/89290240

 这个是个普通的建立线索二叉树的函数,我在他线索的过程中输出每层传进取的参数地址和参数值

void mid_(treelead &t,treelead &pre)  
{
if(t) //如果t非空
{
	mid_(t->lchild,pre);   //进入他的左子树,,
	
	if(t->lchild==NULL)
	{
		t->lchild=pre;
		t->ltag=1;
	}
	
	if(pre!=NULL&&pre->rchild==NULL)
	{
		pre->rchild=t;
		pre->rtag=1;
	}

	  //这是关键 让pre始终指向刚刚被问过的节点t,
	cout<<" &pre:"<<&pre<<endl;//输出p的地址 发现p的地址一直没有变
	cout<<" pre:"<<pre<<endl;//输出pre的值 发现p的地址一直没有变

	cout<<" &t:   "<<&t<<endl;  //输出t的地址
	cout<<" t:   "<<t<<endl;    // 输出t的值
	cout<<endl;
	
	pre=t;
	mid_(t->rchild,pre);   //进入他的右子树
}
}

main函数在下边

int main()
{
treelead p,pre=NULL;

cout<<"t :"<<p<<endl;
cout<<"&t :"<<&p<<endl;
cout<<"pre :"<<pre<<endl;
cout<<"&pre :"<<&pre<<endl;

create(p);
mid_(p,pre);

return 0;
}

下面是结果:  

建立的二叉树形状如图:

在main函数中刚刚创建头节点和pre指针时就输出其地址

中序建立时,其遍历顺序为3 2 4 1 5 6,看下图可知头节点的&t值和第四层,也就是1的&t值是一样的,

怎么说呢?

二叉树在建立的时候,各个节点在内存中的地址就真实的确定了也就是&t的值,也就是pre一开始的值是0,值是会改变的

值就是内存单元中存储的数,而加上&号就是那个内存单元的地址,也就是说,pre一共就用了一个内存单元来存储,但是它进入不同的递归层的时候其值是会改变的,而对于t来说,确实会有6个内存单元地址,那每一层或者说每一个内存单元(t)的值是谁给的呢??pre的。

t :0x413616
&t :0x68fefc
pre :0
&pre :0x68fef8
1 2 3 # # 4 # # 5 # 6 # #
 &pre:0x68fef8
 pre:0
 &t:   0xc60dbc
 t:   0xc60dd8

 &pre:0x68fef8
 pre:0xc60dd8
 &t:   0xc60d9c
 t:   0xc60db8

 &pre:0x68fef8
 pre:0xc60db8
 &t:   0xc60dc0
 t:   0xc60df8

 &pre:0x68fef8
 pre:0xc60df8
 &t:   0x68fefc
 t:   0xc60d98

 &pre:0x68fef8
 pre:0xc60d98
 &t:   0xc60da0
 t:   0xc60e18

 &pre:0x68fef8
 pre:0xc60e18
 &t:   0xc60e20
 t:   0xc60e38

猜你喜欢

转载自blog.csdn.net/lnaruto1234/article/details/89290240