二叉树(链表)

来源:互联网 发布:木工画图软件 编辑:程序博客网 时间:2024/06/06 01:50

搜索 删除 前序 后续遍历都在Node 这类中实现 然后 在树中去调用(注意递归函数的使用???)
Node.h

#include<iostream>using namespace std;template<class T>class Node{public:    int index;    int data;    Node *pLChild;    Node *pRChild;    Node *pParent;    Node()    {        index = 0;        data = 0;        pLChild = NULL;        pRChild = NULL;        pParent = NULL;    }    Node<T> *searchNode(int nodeIndex)    {        if (this->index == nodeIndex)        {            return this;        }        if (this->pLChild != NULL)        {            if (this->pLChild->index == nodeIndex)            {                return this->pLChild;            }        }        if (this->pRChild != NULL)        {            if (this->pRChild->index == nodeIndex)            {                return this->pRChild;            }        }        return NULL;    }    void  deleteNode() //删除结点    {        if (this->pLChild != NULL)        {            this->pLChild->deleteNode();        }        if (this->pRChild != NULL)        {            this->pRChild->deleteNode();        }        if (this->pParent != NULL)        {            if (this->pParent->pRChild == this)            {                this->pParent->pRChild = NULL;            }            if (this->pParent->pLChild == this)            {                this->pParent->pLChild == NULL;            }        }        delete this;    }    void preoderTraversal()//前序遍历 根左右    {        cout << this->index << "  " << this->data;        if (this->pLChild != NULL)        {            this->pLChild->preoderTraversal();        }        if (this->pRChild != NULL)        {            this->pRChild->preoderTraversal();        }    }    void inoderTraversal()//中序遍历  左根右    {        if (this->pLChild != NULL)        {            this->pLChild->preoderTraversal();        }        cout << this->index << "  " << this->data;        if (this->pRChild != NULL)        {            this->pRChild->preoderTraversal();        }    }    void postoderTraversal() //后序遍历左右根    {         if (this->pLChild != NULL)        {            this->pLChild->preoderTraversal();        }        if (this->pRChild != NULL)        {            this->pRChild->preoderTraversal();        }        cout << this->index << "  " << this->data;    }};