二叉树的镜像

纠正一下上图中的描述 只要当前节点有孩子就交换 也包括只有一个孩子的情况

递归代码

 void MirrTree(BtNode* ptr)
 {
	 //  树空             指向树的根节点为空
	 if(ptr == NULL)
		 return ;
	 //只有根 不需要交换
	 if(ptr->leftchild == NULL && ptr->rightchild == NULL)
		 return ;
	 BtNode* tmp = ptr->leftchild ;
	 ptr->leftchild = ptr->rightchild;
	 ptr->rightchild = tmp;
	 if(ptr->leftchild != NULL)
		 MirrTree(ptr->leftchild);
	 if(ptr->rightchild != NULL)
		 MirrTree(ptr->rightchild);

 }

利用栈实现非递归代码 

//利用栈实现非递归
 void swap(BtNode* ptr1,BtNode* ptr2)
 {
	 BtNode* tmp = ptr1;
	 ptr1 = ptr2;
	 ptr2 = tmp;
 }


 void MirrTree1(BtNode* ptr)
 {
	 if(ptr == NULL)
		 return ;
	 stack<BtNode*> st;
	 st.push(ptr);
	 while(!st.empty())
	 {
		 ptr = st.top();st.pop();
		 if(ptr->leftchild != NULL || ptr->rightchild != NULL)
		 {
			 swap(ptr->leftchild,ptr->rightchild);
		 }
		 if(ptr->leftchild != NULL)
			 st.push(ptr->leftchild);
		 if(ptr->rightchild != NULL)
			 st.push(ptr->rightchild);
	 }
 }

利用队列实现非递归

 //利用队列实现 非递归
 void MirrTree3(BtNode* ptr)
 {
	 if(ptr == NULL)
		 return ;
	 queue<BtNode*> qu;
	 qu.push(ptr);
	 while(!qu.empty())
	 {
		 ptr = qu.front();qu.pop();
		 if(ptr->leftchild != NULL || ptr->rightchild != NULL)
		 {
			 swap(ptr->leftchild,ptr->rightchild);
		 }
		 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、付费专栏及课程。

余额充值