交換左右子樹

交換左右子樹

//算法5.5 計算二叉樹的深度,增長左右子數交換等功能
#include<iostream>
using namespace std;

//二叉樹的二叉鏈表存儲表示
typedef struct BiNode
{               
    char data;                      //結點數據域
    struct BiNode *lchild,*rchild;  //左右孩子指針
}BiTNode,*BiTree;

//用算法5.3創建二叉鏈表
void CreateBiTree(BiTree &T)
{   
    //按先序次序輸入二叉樹中結點的值(一個字符),建立二叉鏈表表示的二叉樹T
    char ch;
    cin >> ch;
    if(ch=='#')  T=NULL;            //遞歸結束,建空樹
    else{                           
        T=new BiTNode;
        T->data=ch;                 //生成根結點
        CreateBiTree(T->lchild);    //遞歸建立左子樹
        CreateBiTree(T->rchild);    //遞歸建立右子樹
    }                               //else
}                                   //CreateBiTree

int Depth(BiTree T)
{ 
    int m,n;
    if(T == NULL ) return 0;        //若是是空樹,深度爲0,遞歸結束
    else 
    {                           
        m=Depth(T->lchild);         //遞歸計算左子樹的深度記爲m
        n=Depth(T->rchild);         //遞歸計算右子樹的深度記爲n
        if(m>n) return(m+1);        //二叉樹的深度爲m 與n的較大者加1
        else return (n+1);
    }
}
void InOrderTraverse(BiTree T){  
    //中序遍歷二叉樹T的遞歸算法
    if(T){
        InOrderTraverse(T->lchild);
        cout << T->data;
        InOrderTraverse(T->rchild);
    }
}
void inChangeLR(BiTree &T)
{
    BiTree temp;
    if(T){
        if(T->lchild==NULL&&T->rchild==NULL){
        return;
    } else{
        temp=T->lchild;
        T->lchild = T->rchild;
        T->rchild=temp;
    }
    inChangeLR(T->lchild);
    inChangeLR(T->rchild);
    }
}
void preChangeLR(BiTree &T)
{
BiTree temp;
    if(T){
        inChangeLR(T->lchild);
        if(T->lchild==NULL&&T->rchild==NULL){
        return;
    } else{
        temp=T->lchild;
        T->lchild = T->rchild;
        T->rchild=temp;
    }
    inChangeLR(T->rchild);
    }
}
void postChangeLR(BiTree &T)
{
BiTree temp;
    if(T){
        inChangeLR(T->lchild);
        inChangeLR(T->rchild);
        if(T->lchild==NULL&&T->rchild==NULL){
        return;
    } else{
        temp=T->lchild;
        T->lchild = T->rchild;
        T->rchild=temp;
    }
    
    }
}

int main()
{
    BiTree tree;
    cout<<"請輸入創建二叉鏈表的序列:\n";
    CreateBiTree(tree);

    InOrderTraverse(tree);
    cout<<"數的深度爲:"<<Depth(tree)<<endl;
    cout<<"中序遍歷的結果爲:\n";
    InOrderTraverse(tree);
    cout<<"\n";
    //如下三種執行其中一種
    cout<<"交換後中序遍歷的結果爲:\n";
    inChangeLR(tree);
    InOrderTraverse(tree);
    cout<<"\n";
    cout<<"交換後前序序遍歷的結果爲:\n";
    preChangeLR(tree);
    InOrderTraverse(tree);
    cout<<"\n";
    cout<<"交換後後序遍歷的結果爲:\n";
    postChangeLR(tree);
    InOrderTraverse(tree);

    return 0; 
}
相關文章
相關標籤/搜索