1、有一颗结构如下的树,对其做镜像反转后如下,请写出能实现该功能的代码。注意:请勿对该树做任何假设,它不一定是平衡树,也不一定有序。
1 1
/ | \ / | \
2 3 4 4 3 2
/ | \ / \ | | / \ / | \
1 1
/ | \ / | \
2 3 4 4 3 2
/ | \ / \ | | / \ / | \
6 5 7 8 9 10 10 9 8 7 5 6
思路:将森林转化为二叉树运用了”左子女、右兄弟“的原则,也就是所有兄弟都在右子树上,那么只要反转右子树即可,左子树保持不变。反转右子树使用递归,没遇到一个还未反转的节点就进行反转。
代码如下:包括了建树、遍历数等一些列基本操作。
#include<iostream>
using namespace std;
typedef struct Node{
int key;
struct Node *left,*right;
}TNode,*Tree;
void mirror(Tree root){
if(root == NULL)
return;
if(root->left != NULL){
TNode* p = root->left;
TNode* cur = p->right;
p->right = NULL;
while(cur!=NULL){
TNode* next = cur->right;
cur->right = p;
if(p->left != NULL)
mirror(p);
p = cur;
cur = next;
}
root->left = p;
}
}
void init(Tree &root){
int key[11][2] = {{-1,-1},{1,-1},{2,1},{3,1},{4,1},{5,2},{6,2},{7,2},{8,3},{9,3},{10,4} };
static TNode* ptrs[11];
TNode* tmp;
for(int i=1;i<11;i++){
int t = key[i][1];
TNode* p = new TNode;
p->key = key[i][0];
p->left = p->right = NULL;
ptrs[i] = p;
if(root==NULL)
root = p;
else{
tmp = ptrs[t];
if(tmp->left != NULL){
tmp = tmp->left;
while(tmp->right != NULL)
tmp = tmp->right;
tmp->right = p;
}else{
tmp->left = p;
}
}
}
}
void print_tree(Tree root){
if(root==NULL)
return;
printf("%d\n",root->key);
print_tree(root->right);
print_tree(root->left);
}
void inorder(Tree root){
if(root == NULL)
return ;
printf("%d\n",root->key);
if(root->left != NULL)
inorder(root->left);
if(root->right != NULL)
inorder(root->right);
}
int main(){
Tree root = NULL;
init(root);
mirror(root);
print_tree(root);
return 0;
}