#include<stdio.h>
#include<queue>
template <class T>
struct TreeNode
{
T data;
TreeNode<T>* left;
TreeNode<T>* right;
};
void mirror(TreeNode<int>* root)
{
if (root == nullptr)
return;
std::queue<TreeNode<int>*> q;
q.push(root);
while (!q.empty())
{
TreeNode<int>* r = q.front();
TreeNode<int>* T = r->right;
r->right = r->left;
r->left = T;
if (r->right)
q.push(r->right);
if (r->left)
q.push(r->left);
q.pop();
}
}
TreeNode<int>* BuildTree(int n)
{
TreeNode<int>** arr = new TreeNode<int>*[n];
for (int i = 0; i < n; i++)
{
TreeNode<int>* root = new TreeNode<int>;
root->data = i;
root->left = nullptr;
root->right = nullptr;
arr[i] = root;
}
for (int j = 0; j < n; j++)
{
if(2*j+1<n)
arr[j]->left = arr[2 * j + 1];
if(2*j+2<n)
arr[j]->right = arr[2 * j + 2];
}
return arr[0];
}
TreeNode<int>* BuildTree2(int i, int n)
{
if (i >= n)
return nullptr;
TreeNode<int>* root = new TreeNode<int>;
root->left = BuildTree2(2 * i + 1, n);
root->right = BuildTree2(2*i+2,n);
root->data = i;
return root;
}
int main()
{
TreeNode<int>* root = BuildTree(10);
TreeNode<int>* root2 = BuildTree2(0,10);
mirror(root);
return 0;
}
|