当前位置:编程学习 > C/C++ >>

面试题17:二叉树的镜像

\

例如:下面两棵树互为镜像

\
思路:先序遍历树的每个结点,若遍历到的结点有子节点,则交换它的两个结点。
 

#include "stdafx.h"
#include <iostream>
using namespace std;

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

//构造树的镜像
void Mirror(BinaryTreeNode *pRoot)
{
   if (pRoot != NULL)
   {
	   BinaryTreeNode *pTemp = NULL;
       if (pRoot->m_pLeft != NULL || pRoot->m_pRight != NULL)
       {
		   pTemp = pRoot->m_pLeft;
		   pRoot->m_pLeft = pRoot->m_pRight;
		   pRoot->m_pRight = pTemp;
       }

	   if (pRoot->m_pLeft != NULL)
	   {
		   Mirror(pRoot->m_pLeft);
	   }

	   if (pRoot->m_pRight != NULL)
	   {
		   Mirror(pRoot->m_pRight);
	   }
   }
}

//以先序的方式构建二叉树,输入-1表示结点为空
void CreateBinaryTree(BinaryTreeNode *&pRoot)
{
	int nNodeValue = 0;
	cin >> nNodeValue;	
	if (-1 == nNodeValue)
	{
		return; 
	}
	else
	{
		pRoot = new BinaryTreeNode();
		pRoot->m_nValue = nNodeValue;
		CreateBinaryTree(pRoot->m_pLeft);
		CreateBinaryTree(pRoot->m_pRight);
	}
}

void PrintInOrder(BinaryTreeNode *&pRoot)
{
	if (pRoot != NULL)
	{
		PrintInOrder(pRoot->m_pLeft);
		cout << pRoot->m_nValue << " ";
		PrintInOrder(pRoot->m_pRight);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	BinaryTreeNode *pRoot = NULL;
	CreateBinaryTree(pRoot);
	PrintInOrder(pRoot);
	cout << endl;
    
	Mirror(pRoot);
	PrintInOrder(pRoot);
	cout << endl;

	system("pause");
	return 0;
}

 

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,