二叉樹C++實現

說明

這是個經典問題,其中指針,結構是以後學習的基礎,在此記錄一下

#include <stdio.h>
#include <iostream>
using namespace std;
typedef int TYPE;

class BinTree{
public:
    struct Node{
        TYPE data;
        Node *lchild, *rchild;
        Node(TYPE d = TYPE()):data(d), lchild(NULL), rchild(NULL){};
    };
    typedef Node *NodePointer;
private:
    NodePointer root;
public:
    BinTree();
    BinTree(const TYPE *a, int size, int &index, const TYPE invalid){
        root = MakeTree(a, size, index, invalid);
    }
    ~BinTree();

    void PreOrder(){
        Pre(root);
        cout<<endl;
    };

    void InOrder(){
        In(root);
        cout<<endl;
    };

    void PostOrder(){
        Post(root, 0);
        cout<<endl;
    };
private:
    NodePointer MakeTree(const TYPE *a, int size, int &index, const TYPE invalid){
        NodePointer node = NULL;
        if (index < size && a[index] != invalid){
            node = new Node(invalid);
            cout<<"index: "<<index<<" a[index]: "<<a[index]<<endl;
            node->data = a[index];
            node->lchild = MakeTree(a, size, ++index, invalid);
            node->rchild = MakeTree(a, size, ++index, invalid);
        }
        return node;
    }
    void DestoryTree(NodePointer T){
        if (T){
            DestoryTree(T->lchild);
            DestoryTree(T->rchild);
            delete T;
            T = NULL;
        }
    }
    void Pre(NodePointer all_node);
    void In(NodePointer all_node);
    void Post(NodePointer all_node, int level);
};

BinTree::BinTree(){
    root = NULL;
}

BinTree::~BinTree(){
    DestoryTree(root);
}

void BinTree::Pre(NodePointer root1){
    NodePointer root = root1;
    if (root){
        cout<<root->data<<endl;
        cout<<"left: ";
        Pre(root->lchild);
        cout<<"right: ";
        Pre(root->rchild);       
    }
}

void BinTree::In(NodePointer root){
    if (root){
        In(root->lchild);
        cout<<root->data<<" ";
        In(root->rchild);
    }
}

void BinTree::Post(NodePointer root1,int level){
     NodePointer root = root1;
    if (root){
        Post(root->lchild, ++level);
        Post(root->rchild, ++level);
        cout<<"level: "<<level<<" data: "<<root->data<<" "<<endl;
    }
}

int main(int argc, char const *argv[])
{
    TYPE list[6]= {1,2,0,3,4,0};
    int i = 0;
    int &index = i;
    BinTree * b = new BinTree(list, 6, index, 0);
    b->PostOrder();
    delete b;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章