镜像反转森林

1、有一颗结构如下的树,对其做镜像反转后如下,请写出能实现该功能的代码。注意:请勿对该树做任何假设,它不一定是平衡树,也不一定有序。
            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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值