您的位置:首页 > 理论基础 > 数据结构算法

【学习点滴-数据结构-二叉树】二叉树转换为其镜像。

2012-05-31 15:45 585 查看
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <queue>
#include <iostream> 
#include <malloc.h>
#define LEAF -1
using namespace std; 

typedef struct BTreeNode{
     BTreeNode* lchild;
     BTreeNode* rchild;
     int value;       
        
}BTreeNode,*Btree;

BTreeNode* createTree(){
     BTreeNode* T;
     int t;      
     scanf("%d",&t);
     if(t == LEAF){
          T = NULL;
     }else{
          T = (BTreeNode *) malloc(sizeof(BTreeNode));
          T->value = t;
          T->lchild = createTree();
          T->rchild = createTree();    
     }
     return T;
}
//注意swap()函数。 
void swap(BTreeNode ** left,BTreeNode** right){
     BTreeNode * tmp = *left;
     *left = *right;
     *right = tmp;    
}

void treeMirror(BTreeNode* &root){
     if(root == NULL){
         return ;        
     }
     swap(&(root->lchild),(&root->rchild));
     treeMirror(root->lchild);
     treeMirror(root->rchild);        
}

void preOrder(BTreeNode* root){
     if(root != NULL){
         printf("%d ",root->value);
     }
     if(root->lchild != NULL){
         preOrder(root->lchild);            
     }
     if(root->rchild !=NULL){
         preOrder(root->rchild);
     }
}

void mirrorNonRecursive(BTreeNode * &root){
     if(root == NULL){
         return ;        
     } 
     queue<BTreeNode*> que;
     que.push(root);
     while(!que.empty()){
          BTreeNode *tmp = que.front();
          que.pop(); 
          swap(&(tmp->lchild),&(tmp->rchild));
          if(tmp->lchild != NULL){
              que.push(tmp->lchild);               
          }
          if(tmp->rchild != NULL){
              que.push(tmp->rchild); 
          }                    
     } 
     
} 

main(){
    BTreeNode * root;
    root = createTree();
    printf("Before Mirror : \n");
    preOrder(root);
    //treeMirror(root);
    //printf("After Mirror : \n");
    //preOrder(root);
    printf("After MirrorNonRecur : \n");
    mirrorNonRecursive(root);
    preOrder(root); 
    system("pause");
    return 0;       
       
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: