递归生成镜像树
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
class TreeNode {
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int value):val(value),left(nullptr),right(nullptr){}
};
TreeNode *mirror(TreeNode *root) {
if (!root) {
return nullptr;
}
TreeNode *node = root->right;
root->right = mirror(root->left);
root->left = mirror(node);
return root;
}
int main() {
TreeNode *root = new TreeNode(4);
TreeNode *a = new TreeNode(2);
TreeNode *b = new TreeNode(7);
TreeNode *c = new TreeNode(1);
TreeNode *d = new TreeNode(3);
TreeNode *e = new TreeNode(6);
TreeNode *f = new TreeNode(9);
root->left = a;
root->right = b;
a->left = c;
a->right = d;
b->left = e;
b->right = f;
TreeNode *res = mirror(root);
queue<TreeNode*> s;
s.push(res);
while (!s.empty()) {
int len = s.size();
for (int i = 0; i < len; ++i) {
TreeNode *cur = s.front();
cout << cur->val << " ";
if (cur->left) {
s.push(cur->left);
}
if (cur->right) {
s.push(cur->right);
}
s.pop();
}
}
cout << endl;
system("pause");
}
辅助栈实现
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
class TreeNode {
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int value):val(value),left(nullptr),right(nullptr){}
};
TreeNode *mirror(TreeNode *root) {
if (root == nullptr) return nullptr;
stack<TreeNode*> stack;
stack.push(root);
while (!stack.empty())
{
TreeNode* node = stack.top();
stack.pop();
if (node->left != nullptr) stack.push(node->left);
if (node->right != nullptr) stack.push(node->right);
TreeNode* tmp = node->left;
node->left = node->right;
node->right = tmp;
}
return root;
}
int main() {
TreeNode *root = new TreeNode(4);
TreeNode *a = new TreeNode(2);
TreeNode *b = new TreeNode(7);
TreeNode *c = new TreeNode(1);
TreeNode *d = new TreeNode(3);
TreeNode *e = new TreeNode(6);
TreeNode *f = new TreeNode(9);
root->left = a;
root->right = b;
a->left = c;
a->right = d;
b->left = e;
b->right = f;
TreeNode *res = mirror(root);
queue<TreeNode*> s;
s.push(res);
while (!s.empty()) {
int len = s.size();
for (int i = 0; i < len; ++i) {
TreeNode *cur = s.front();
cout << cur->val << " ";
if (cur->left) {
s.push(cur->left);
}
if (cur->right) {
s.push(cur->right);
}
s.pop();
}
}
cout << endl;
system("pause");
}