1. 程式人生 > >資料結構篇:二叉樹(四:交換左右子樹)

資料結構篇:二叉樹(四:交換左右子樹)

應用遞迴思想

如果結點不為空,就交換其左右子樹,而待交換的左右子樹,我們不需要關心是否為空。

void Tree::ExChangeTree(BiTree *T) {

    BiTree *temp = new BiTree;
    if (T)
    {
        temp = T->rchild;
        T->rchild = T->lchild;
        T->lchild = temp;
        ExChangeTree(T->lchild);
        ExChangeTree(T->rchild);
    }
    else
    {
        return;
    }
}

執行截圖

完整程式

//
// Created by 煙雨迷離半世殤 on 2018/11/28.
//

#include <iostream>
#include <string.h>

using namespace std;

struct BiTree {
    char data;
    BiTree *lchild, *rchild;
};

class Tree {
    BiTree *pt;
public :
    Tree() {
        pt = NULL;
    }

    BiTree *PreCreateBiTree();

    void PreOrderTraverse(BiTree *T);

    void InOrderTraverse(BiTree *T);

    void LastOrderTraverse(BiTree *T);

    void ExChangeTree(BiTree *T);
};

BiTree *Tree::PreCreateBiTree() {
    BiTree *T;
    char c;
    cin >> c;
    if (c == '#')
    {
        T = NULL;
    }
    else
    {
        T = new BiTree;
        if (!T)
        {
            cout << "請求記憶體失敗。" << endl;
        }
        else
        {
            T->data = c;
        }
        T->lchild = PreCreateBiTree();
        T->rchild = PreCreateBiTree();
    }
    return T;
}

void Tree::PreOrderTraverse(BiTree *T) {
    if (!T)
    {
        return;
    }
    else
    {
        cout << T->data << " ";
        PreOrderTraverse(T->lchild);
        PreOrderTraverse(T->rchild);
    }
}

void Tree::InOrderTraverse(BiTree *T) {
    if (!T)
    {
        return;
    }
    else
    {
        InOrderTraverse(T->lchild);
        cout << T->data << " ";
        InOrderTraverse(T->rchild);
    }
}

void Tree::LastOrderTraverse(BiTree *T) {
    if (!T)
    {
        return;
    }
    else
    {
        LastOrderTraverse(T->lchild);
        LastOrderTraverse(T->rchild);
        cout << T->data << " ";
    }
}

void Tree::ExChangeTree(BiTree *T) {

    BiTree *temp = new BiTree;
    if (T)
    {
        temp = T->rchild;
        T->rchild = T->lchild;
        T->lchild = temp;
        ExChangeTree(T->lchild);
        ExChangeTree(T->rchild);
    }
    else
    {
        return;
    }
}


int main() {
    Tree tree;
    BiTree *biTree;
    cout << "請以先序順序輸入數元素,以'#'代表虛空元素" << endl;
    biTree = tree.PreCreateBiTree();
    cout << "先序遍歷結果為: " << endl;
    tree.PreOrderTraverse(biTree);
    cout << endl;
    cout << "中序遍歷結果為: " << endl;
    tree.InOrderTraverse(biTree);
    cout << endl;
    cout << "後序遍歷結果為: " << endl;
    tree.LastOrderTraverse(biTree);
    cout << "交換左右子樹結果為: " << endl;
    tree.ExChangeTree(biTree);
    cout << "先序遍歷結果為: " << endl;
    tree.PreOrderTraverse(biTree);
    cout << endl;
    cout << "中序遍歷結果為: " << endl;
    tree.InOrderTraverse(biTree);
    cout << endl;
    cout << "後序遍歷結果為: " << endl;
    tree.LastOrderTraverse(biTree);
    return 0;
}