题目
操作给定的二叉树,将其变换为源二叉树的镜像
思路
利用广度优先遍历的思想。利用一个队列,每次将队首元素的左右孩子先交换,再入队,递归如此。
示例
利用前序和中序生成一棵树:
pre:8,6,5,7,10,9,11,12
mid:5,6,7,8,9,10,11,12
输出(广度优先遍历):
8 10 6 11 9 7 5 12
代码
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x)
:val(x),left(nullptr),right(nullptr){
}
};
class Solution{
public:
// 输出树的镜像
TreeNode* Mirror(TreeNode* tree){
queue<TreeNode*> root;
root.push(tree);
TreeNode* exchange_node(nullptr);
// 如果空树,直接返回
if (tree == nullptr)
return tree;
while (!root.empty()){
// 如果左子树和右子树都为空跳出循环
if(root.front()->left == nullptr && root.front()->right == nullptr)
break;
// 如果左子树为空,则把右子树赋值到左子树,然后把右子树置空
else if(root.front()->left == nullptr) {
root.front()->left = root.front()->right;
root.front()->right = nullptr;
root.push(root.front()->left);
root.pop();
}
// 如果右子树为空,则把左子树复制到右子树上,然后把左子树置空
else if (root.front()->right == nullptr){
root.front()->right = root.front()->left;
root.front()->left = nullptr;
root.push(root.front()->right);
root.pop();
}
// 左右子树都存在,则把左右子树交换位置
else {
exchange_node = root.front()->left;
root.front()->left = root.front()->right;
root.front()->right = exchange_node;
if (root.front()->left != nullptr)
root.push(root.front()->left);
if (root.front()->right != nullptr)
root.push(root.front()->right);
root.pop();
}
}
return tree;
}
// 根据前序和中序构造一棵树,用来测试
TreeNode* createTree(vector<int> pre, vector<int> mid){
cout << " mark1 " << endl;
TreeNode* tree(nullptr);
tree = createTree(pre,0,pre.size()-1, mid, 0, mid.size()-1);
return tree;
}
// 广度优先输出树的结点
void outTreeBFS(TreeNode *root){
queue<TreeNode*> tree;
tree.push(root);
while (!tree.empty()){
cout << tree.front()->val << " ";
if (tree.front()->left != nullptr)
tree.push(tree.front()->left);
if (tree.front()->right != nullptr)
tree.push(tree.front()->right);
tree.pop();
}
}
private:
TreeNode* createTree(vector<int> pre,int pre_start, int pre_end,
vector<int> mid,int mid_start, int mid_end){
if(pre_start > pre_end || mid_start > mid_end){
return nullptr;
}
TreeNode* node = new TreeNode(0);
for (int i = mid_start; i <= mid_end ; ++i) {
if (mid[i] == pre[pre_start]){
node->val = mid[i];
node->left = createTree(pre, pre_start+1, pre_start+i-mid_start,
mid, mid_start,i-1);
node->right = createTree(pre, pre_start+i-mid_start+1, pre_end,
mid, i+1, mid_end);
break;
}
}
return node;
}
};
int main(){
vector<int> pre = {8,6,5,7,10,9,11,12};
vector<int> mid = {5,6,7,8,9,10,11,12};
Solution re;
re.outTreeBFS(re.createTree(pre,mid));
re.outTreeBFS(re.Mirror(re.createTree(pre,mid)));
return 0;
}