您的位置:首页 > 职场人生

面试题17:二叉树的镜像

2013-07-21 21:39 218 查看


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



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

代码:

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: