您的位置:首页 > 其它

二叉树镜像

2014-03-11 21:43 239 查看
/******************************************************************
题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像。
******************************************************************/
#include<stdio.h>

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

BinaryTreeNode* createBinaryTreeNode(int value)
{
	BinaryTreeNode* pNewNode = new BinaryTreeNode();
	pNewNode->m_nValue = value;
	pNewNode->m_pLeft = NULL;
	pNewNode->m_pRight = NULL;
	return pNewNode;
}
void connectBinaryTreeNode(BinaryTreeNode* pParent,BinaryTreeNode* pLeftChild,
						   BinaryTreeNode* pRightChild)
{
	if(!pParent)
		return;

	pParent->m_pLeft = pLeftChild;
	pParent->m_pRight = pRightChild;
}
void ptintBinaryTreeNode(BinaryTreeNode* pNode)
{
	if(pNode)
	{
		printf("Node's valuse is %d\n",pNode->m_nValue);
		if(pNode->m_pLeft)
			printf("Node's left child value is %d\n",pNode->m_pLeft->m_nValue);
		else
			printf("Node's left child value is NULL\n");
		if(pNode->m_pRight)
			printf("Node's right child value is %d\n",pNode->m_pRight->m_nValue);
		else
			printf("Node's right child value is NULL\n");
	}
	else
	{
		printf("Node's valuse is NULL\n");
	}
}
void printTree(BinaryTreeNode* pRoot)
{
	if(pRoot)
	{
		ptintBinaryTreeNode(pRoot);
	if(pRoot->m_pLeft)
		printTree(pRoot->m_pLeft);
	if(pRoot->m_pRight)
		printTree(pRoot->m_pRight);
	}
}

void mirrorOfBinaryTree(BinaryTreeNode* pRoot)
{
	if(pRoot == NULL)
		return;
	
	BinaryTreeNode* pNode;
	pNode = pRoot->m_pLeft;
	pRoot->m_pLeft = pRoot->m_pRight;
	pRoot->m_pRight = pNode;
	
	if(pRoot->m_pLeft)
		mirrorOfBinaryTree(pRoot->m_pLeft);
	if(pRoot->m_pRight)
		mirrorOfBinaryTree(pRoot->m_pRight);

}
//单元测试
void test1()
{
	BinaryTreeNode* pNode1 = createBinaryTreeNode(8);
	BinaryTreeNode* pNode2 = createBinaryTreeNode(6);
	BinaryTreeNode* pNode3 = createBinaryTreeNode(10);
	BinaryTreeNode* pNode4 = createBinaryTreeNode(5);
	BinaryTreeNode* pNode5 = createBinaryTreeNode(7);
	BinaryTreeNode* pNode6 = createBinaryTreeNode(9);
	BinaryTreeNode* pNode7 = createBinaryTreeNode(11);

	connectBinaryTreeNode(pNode1,pNode2,pNode3);
	connectBinaryTreeNode(pNode2,pNode4,pNode5);
	connectBinaryTreeNode(pNode3,pNode6,pNode7);

	mirrorOfBinaryTree(pNode1);
	printTree(pNode1);

}

int main()
{
	test1();
	return 0;
}
void MirrorIteratively(BinaryTreeNode* pRoot){    if(pRoot == NULL)        return;    std::stack<BinaryTreeNode*> stackTreeNode;    stackTreeNode.push(pRoot);    while(stackTreeNode.size() > 0)    {        BinaryTreeNode *pNode = stackTreeNode.top();        stackTreeNode.pop();        BinaryTreeNode *pTemp = pNode->m_pLeft;        pNode->m_pLeft = pNode->m_pRight;        pNode->m_pRight = pTemp;        if(pNode->m_pLeft)            stackTreeNode.push(pNode->m_pLeft);        if(pNode->m_pRight)            stackTreeNode.push(pNode->m_pRight);    }}
==参考剑指offer

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: