面试题27:二叉树的镜像(递归+非递归)C++

#include<iostream>
#include<stack>
struct BinaryTreeNode
{
	int m_nValue;
	BinaryTreeNode* pChildenLeft, * pChildenRight;
	BinaryTreeNode(int _value):m_nValue(_value),pChildenLeft(nullptr),pChildenRight(nullptr){}
};

一、递归

void MirrorRecusively(BinaryTreeNode* root)
{
	if (root == nullptr)return;
	if (root->pChildenLeft == nullptr && root->pChildenRight == nullptr)
		return;
	BinaryTreeNode* pTempNode = root->pChildenLeft;
	root->pChildenLeft = root->pChildenRight;
	root->pChildenRight = pTempNode;
	if (root->pChildenLeft)
		MirrorRecusively(root->pChildenLeft);
	if (root->pChildenLeft)
		MirrorRecusively(root->pChildenRight);
}

二、循环遍历,利用容器进行镜像交换

void Mirror(BinaryTreeNode* root)
{
	if (root == nullptr)return;
	std::stack<BinaryTreeNode*>mirr;
	mirr.push(root);
	while (!mirr.empty())
	{
		BinaryTreeNode* parent = mirr.top();
		mirr.pop();
		BinaryTreeNode* pTempNode = parent->pChildenLeft;
		parent->pChildenLeft = parent->pChildenRight;
		parent->pChildenRight = pTempNode;
		if (parent->pChildenLeft)
			mirr.push(parent->pChildenLeft);
		if (parent->pChildenRight)
			mirr.push(parent->pChildenRight);
	}
}
发布了107 篇原创文章 · 获赞 28 · 访问量 1964

猜你喜欢

转载自blog.csdn.net/qq_38994205/article/details/104426061