二叉树的镜像

本文介绍了一种通过递归方式实现二叉树镜像的方法。首先定义了二叉树节点结构,接着提供了插入节点的功能,并实现了镜像递归函数。最后通过随机生成数值创建二叉树并展示镜像前后效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include"BinaryTree.h"

void MirrorRecursively(BinaryTreeNode* pNode)
{
	if(pNode==NULL||pNode->m_pLeft==NULL&&pNode->m_pRight==NULL)
		return;
	BinaryTreeNode *pTemp=pNode->m_pLeft;
	pNode->m_pLeft=pNode->m_pRight;
	pNode->m_pRight=pTemp;
	if(pNode->m_pLeft)
		MirrorRecursively(pNode->m_pLeft);
	if(pNode->m_pRight)
		MirrorRecursively(pNode->m_pRight);
}
<pre name="code" class="cpp">#include<iostream>
using namespace std;

struct BinaryTreeNode
{
	int m_nValue;
	BinaryTreeNode* m_pLeft;
	BinaryTreeNode* m_pRight;
};

BinaryTreeNode* insert(BinaryTreeNode** pRoot,int value)
{
	if(*pRoot==NULL)
	{
		*pRoot=new BinaryTreeNode;
		(*pRoot)->m_nValue=value;
		(*pRoot)->m_pLeft=NULL;
		(*pRoot)->m_pRight=NULL;
		return *pRoot;
	}
	if(value<(*pRoot)->m_nValue)
		(*pRoot)->m_pLeft=insert(&(*pRoot)->m_pLeft,value);
	else
		(*pRoot)->m_pRight=insert(&(*pRoot)->m_pRight,value);
	return *pRoot;
}


void printBinaryTree(BinaryTreeNode* pRoot)
{
	if(pRoot==NULL)
		return;
	cout<<pRoot->m_nValue<<" ";
	printBinaryTree(pRoot->m_pLeft);
	printBinaryTree(pRoot->m_pRight);
}	
<pre name="code" class="cpp">#include"MirrorRecursively.h"
#include<ctime>
#include<cstdlib>
int main()
{
	BinaryTreeNode* pRoot1=NULL;
	srand((unsigned int)(time(NULL)));
	for(int i=0;i<10;i++)
	{
		int randnum=rand()%100;
		insert(&pRoot1,randnum);
	}
	cout<<"Tree1: ";
	printBinaryTree(pRoot1);
	cout<<endl;
	MirrorRecursively(pRoot1);
	cout<<"Mirror: ";
	printBinaryTree(pRoot1);
	cout<<endl;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值