您的位置:首页 > 其它

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

2016-10-21 17:09 337 查看
// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。

//

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