操作给定的二叉树,将其变换为源二叉树的镜像。

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//

include "stdafx.h"

include "stdafx.h"

include

include

include

include

include

include

include

include

using namespace std;

struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};

class Solution {
public:
void Mirror(TreeNode* &pRoot) {

if (pRoot != NULL && (pRoot->left != NULL || pRoot->right != NULL))
{
TreeNode *temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;

Mirror(pRoot->left);
Mirror(pRoot->right);
}
}

//先序遍历构建二叉树
void preCreate(TreeNode* &T)
{
int num;
cin >> num;
if (num == 0) T = NULL;
else
{
T = new TreeNode(num);
preCreate(T->left);
preCreate(T->right);
}
}

//递归的方法先序遍历二叉树
void preOrder(TreeNode* &T)
{
if (T == NULL) return;
else
{
cout << T->val << " ";
preOrder(T->left);
preOrder(T->right);

}
}

};
int main()
{

Solution so;

TreeNode* bi;

so.preCreate(bi);
cout << "创建二叉树成功!" << endl;

cout << "原二叉树先序遍历:" << endl;
so.preOrder(bi);
cout << endl;

cout << "镜像二叉树先序遍历:" << endl;
so.Mirror(bi);
so.preOrder(bi);
cout << endl;

cout << endl;
return 0;
}

posted @ 2016-10-21 17:09  wdan2016  阅读(372)  评论(0)    收藏  举报