第61課 二叉樹的存儲結構

1. 存儲結構node

(1)繼承關係ide

 

(2)設計要點函數

  ①BTree爲二叉樹結構,每一個結點最多隻有兩個後繼結點this

  ②BTreeNode只包含4個固定的公有成員(value、parent、left、right)spa

  ③實現樹結構的全部操做(增、刪、查等)設計

 

2. BTreeNode的設計與實現指針

 

(1)繼承自TreeNode,內含parent、left、right指針,分別指向父結點、左孩子、右孩子結點。code

(2)與通用樹結點同樣,提供工廠方法NewNode對象

(3)設置m_flag標誌,用於標識結點是否存儲於堆空間中。blog

3. BTree的設計與實現

 

(1)繼承自Tree

(2)內部組合使用BTreeNode

//Tree.h(重構)

#ifndef _TREE_H_
#define _TREE_H_

#include "Object.h"
#include "SharedPointer.h"
#include "Iterator.h"

namespace DTLib {

//樹結點的定義
template <typename T>
class TreeNode : public Object
{
protected:
    bool m_flag; //標識結點是否位於堆空間?

    TreeNode(const TreeNode<T>&);
    TreeNode<T> & operator=(const TreeNode<T>&);

    //禁止外部手動調用new
    void* operator new(unsigned int size) throw()
    {
        return Object::operator new(size);
    }
public:
    T value;
    TreeNode<T>* parent;

    TreeNode()
    {
        parent = NULL;
        m_flag = false;
    }

    bool flag()
    {
        return m_flag;
    }

    virtual ~TreeNode() = 0;
};

template <typename T>
TreeNode<T>::~TreeNode()
{
}

//樹的定義
template <typename T>
class Tree : public Object
{
public:
    typedef TreeNode<T> Node;
protected:
    Node* m_root;

    //禁止樹之間的複製
    Tree(const Tree<T>&);
    Tree<T> & operator=(const Tree<T>&);

public:
    Tree(){m_root = NULL;}
    virtual bool insert(Node* node) = 0; //插入結點
    virtual bool insert(const T& value, Node* parent) = 0;
    //刪除節點(注意,返回被刪除的子樹!)
    virtual SharedPointer<Tree<T> > remove(const T& value) = 0; //刪除結點
    virtual SharedPointer<Tree<T> > remove(Node* node) = 0;
    virtual Node* find(const T& value) const = 0; //查找節點
    virtual Node* find(Node* node) const = 0;
    virtual Node* root() const = 0; //獲取根結點
    virtual int degree() const = 0; //樹的度
    virtual int count() const = 0;  //樹的結點數目
    virtual int height() const = 0; //樹的高度
    virtual void clear() = 0;       //清空樹

};

//前向迭代器(樹型)
template<class T, class Ref, class Ptr, class Node>
struct TreeIterator
{
    typedef TreeIterator<T, T&, T*, Node>   iterator;
    typedef TreeIterator<T, const T&, const T*, Node> const_iterator;
    typedef TreeIterator<T, Ref, Ptr, Node>   self;

    typedef ForwardIterator_tag  iterator_category; //迭代器類型
    typedef T   value_type; //值類型
    typedef Ptr pointer;    //指針類型
    typedef Ref  reference; //引用類型
    typedef ptrdiff_t difference_type;
    typedef Node*  node_type; //節點指針類型

    node_type  cursor;  //迭代器當前所指節點

    TreeIterator(node_type x) : cursor(x){}
    TreeIterator(const iterator& x) : cursor(x.cursor){}

    //重載==和!=操做符
    bool operator ==(const self& x) const
    {
        return cursor == x.cursor;
    }

    bool operator !=(const self& x) const
    {
        return cursor != x.cursor;
    }

    //重載*和->操做符
    reference operator*() const
    {
        return (*cursor).value;
    }

    pointer operator->() const
    {
        return &(operator*());
    }

};

}

#endif // _TREE_H_

//GTree.h(重構)

#ifndef _GTREE_H_
#define _GTREE_H_

#include "Tree.h"
#include "LinkList.h"
#include "Exception.h"
#include "Iterator.h"
#include "LinkQueue.h"

namespace DTLib {

//通用樹結點定義
template <typename T>
class GTreeNode : public TreeNode<T>
{

public:
    LinkList<GTreeNode<T>*> childs;

    //工廠模式:要獲取GTreeNode的堆空間對象,只能從這裏拿
    static GTreeNode<T>* NewNode()
    {
        GTreeNode<T>* ret = new GTreeNode<T>;
        if(ret != NULL){
            ret->m_flag = true;
        }

        return ret;
    }
};

//前向迭代器(樹型)
template<class T, class Ref, class Ptr, class Node>
struct GTreeIterator : public TreeIterator<T, Ref, Ptr, Node>
{
private:
    LinkQueue<Node*> m_queue;

public:

    typedef GTreeIterator<T, T&, T*, Node>   iterator;
    typedef GTreeIterator<T, const T&, const T*, Node> const_iterator;
    typedef GTreeIterator<T, Ref, Ptr, Node>   self;

    typedef ForwardIterator_tag  iterator_category; //迭代器類型
    typedef T   value_type; //值類型
    typedef Ptr pointer;    //指針類型
    typedef Ref  reference; //引用類型
    typedef ptrdiff_t difference_type;
    typedef Node*  node_type; //節點指針類型

    GTreeIterator(const node_type& x) :  TreeIterator<T, Ref, Ptr, Node>(x){m_queue.clear();m_queue.enQueue(x);}
    //前置++
    self& operator++()
    {
        this->cursor = NULL;

        if(m_queue.length() > 0 ){

            //當前結點的孩子結點進入隊列中
            Node* curr = (Node*) m_queue.front();
            m_queue.deQueue();

            typename LinkList<Node*>::iterator iter = curr->childs.begin();
            while(iter != curr->childs.end())
            {
                m_queue.enQueue(*iter);
                ++iter;
            }

            if(m_queue.length() > 0 )
                this->cursor = m_queue.front();
        }

        return *this;
    }

    //後置++
    self operator++(int)
    {
        self tmp = *this;
        ++(*this);

        return tmp;
    }
};

//通用樹的定義
template <typename T>
class GTree : public Tree<T>
{
public:
    typedef typename Tree<T>::Node Node;
    typedef GTreeNode<T> GNode;

protected:
    GNode* find(GNode* node, const T& value) const
    {
        GNode* ret = NULL;

        if(node != NULL){
            if(node->value == value){
                ret = node;
            }else{
                //遍歷node的孩子(每一個孩子結點又都是一棵子樹)
                typename LinkList<GNode*>::iterator iter = node->childs.begin();
                while((iter != node->childs.end()) && (ret == NULL)){
                    ret = find(*iter, value);
                    ++iter;
                }
            }
        }

        return ret;
    }

    GNode* find(GNode* node, GNode* obj) const
    {
        GNode* ret = NULL;

        if(node == obj){
            ret = node;
        }else{
            if( node != NULL){
                //遍歷node的孩子(每一個孩子結點又都是一棵子樹)
                typename LinkList<GNode*>::iterator iter = node->childs.begin();
                while((iter != node->childs.end()) && (ret == NULL)){
                    ret = find(*iter, obj);
                    ++iter;
                }
            }
        }

        return ret;
    }

    void free(GNode* node) //清除某個節點(含其中的子樹)
    {
        if (node != NULL){
            //遍歷node的孩子
            typename LinkList<GNode*>::iterator iter = node->childs.begin();
            while(iter != node->childs.end()){
                free(*iter);
                ++iter;
            }

            if(node->flag()) //只有當node是來自堆空間對象時,才須要delete
                delete node; //node釋放時,childs(鏈表會被自動釋放)
        }
    }

    void remove(GNode* node, GTree<T>*& ret)
    {
        ret = new GTree<T>();

        if(ret != NULL){
            if(root() == node){
                this->m_root = NULL;
            }else{
                LinkList<GNode*>& childs = dynamic_cast<GNode*>(node->parent)->childs;
                childs.remove(childs.find(node)); //node指針從LinkList鏈表中移除

                node->parent = NULL;
            }

            ret->m_root = node;

        }else{
            THROW_EXCEPTION(NotEnoughMemoryException, "No memory to create new tree...");
        }
    }

    int count(GNode* node) const
    {
        int ret = 0;

        if (node != NULL){

            ret = 1;
            typename LinkList<GNode*>::iterator iter = node->childs.begin();
            while(iter != node->childs.end()){
                ret += count(*iter);
                ++iter;
            }
        }

        return ret;
    }

    int degree(GNode* node) const
    {
        int ret = 0;

        if (node != NULL){

            ret = node->childs.length();
            typename LinkList<GNode*>::iterator iter = node->childs.begin();
            while(iter != node->childs.end()){
                int temp =  degree(*iter);

                if(ret < temp){
                    ret = temp;
                }

                ++iter;
            }
        }

        return ret;
    }

    int height(GNode* node) const
    {
        int ret = 0;

        if (node != NULL){

            typename LinkList<GNode*>::iterator iter = node->childs.begin();

            while(iter != node->childs.end()){
                int temp =  height(*iter);

                if(ret < temp){
                    ret = temp;
                }

                ++iter;
            }

            ret += 1;
        }

        return ret;
    }

public:
    GTree()
    {

    }

    bool insert(Node* node) //插入結點
    {
        bool ret = true;

        if(node != NULL){
            if(this->m_root == NULL){
                this->m_root = node;
                node->parent = NULL;
            }else{
                GNode* np = find(node->parent); //np: node parent
                if(np != NULL){
                    //查找np結點下,是否己經存在node結點?若己經存在,則不插入。
                    GNode* nd = dynamic_cast<GNode*>(node);//nd: node

                    if(np->childs.find(nd) < 0){
                        np->childs.insert(nd); //插入到鏈表末尾
                    }
                }else{
                    THROW_EXCEPTION(InvalidOperationException, "Invalid parent tree Node...");
                }
            }
        }else{
            THROW_EXCEPTION(InvalidParameterException, "Paramter node can't be NULL!");
        }

        return ret;
    }

    bool insert(const T& value, Node* parent)
    {
        bool ret = true;

        GNode* node = GNode::NewNode(); //new GNode();

        if(node != NULL){
            node->parent = parent;
            node->value = value;
            ret = insert(node); //調用重載的insert(Node*)函數。
        }else{
            THROW_EXCEPTION(NotEnoughMemoryException, "Not enough memory to insert new node...");
        }

        return ret;
    }

    //刪除節點(注意,返回被刪除的子樹!)
    SharedPointer<Tree<T> > remove(const T& value) //刪除結點
    {
        GTree<T>* ret = NULL;

        GNode* node = find(value);
        if(node == NULL){
            THROW_EXCEPTION(InvalidParameterException, "Parameter node is invalid...");
        }else{
            remove(node, ret);
        }

        return ret;
    }

    SharedPointer<Tree<T> > remove(Node* node)
    {
        GTree<T>* ret = NULL;
        node = find(node); //node是否在當前樹中

        if(node == NULL){
            THROW_EXCEPTION(InvalidParameterException, "Can not find the node via parameter value...");
        }else{
            remove(dynamic_cast<GNode*>(node), ret);
        }

        return ret;
    }

    GNode* find(const T& value) const //查找節點
    {
        return find(root(), value);
    }

    //注意返回值由Node*改成GNode*(賦值兼容原則)
    GNode* find(Node* node) const
    {
        return find(root(), dynamic_cast<GNode*>(node));
    }

    GNode* root() const
    {
        return dynamic_cast<GNode*>(this->m_root);
    }

    int degree() const  //樹的度
    {
        return degree(root());
    }

    int count() const   //樹的結點數目
    {
        return count(root());
    }

    int height() const  //樹的高度
    {
        return height(root());
    }

    void clear()        //清空樹
    {
        free(root());
        this->m_root = NULL;
    }

    ~GTree()
    {
        clear();
    }
public:
    typedef GTreeIterator<T, T&, T*, GNode>   iterator;
    typedef GTreeIterator<T, const T&, const T*, GNode> const_iterator;

    iterator begin()
    {
        //調用GIterator(Node_type)構造函數
        return (GNode*)(this->m_root);
    }

    iterator end()
    {
        return  NULL;
    }

    const_iterator begin() const
    {
        //調用GIterator(Node_type)構造函數
        return (GNode*)(root());
    }

    virtual const iterator end() const
    {
        return  NULL;
    }
};

}

#endif // _GTREE_H_
View Code

//BTree.h

#ifndef _BTREE_H_
#define _BTREE_H_

#include "Tree.h"

namespace DTLib
{

template<typename T>
class BTreeNode : public TreeNode<T>
{
public:
    BTreeNode<T>* left;
    BTreeNode<T>* right;

    BTreeNode()
    {
        left = NULL;
        right = NULL;
    }

    //工廠模式:要獲取BTreeNode的堆空間對象,只能從這裏拿
    static BTreeNode<T>* NewNode()
    {
        BTreeNode<T>* ret = new BTreeNode<T>;
        if(ret != NULL){
            ret->m_flag = true;
        }

        return ret;
    }
};

template<typename T>
class BTree : public Tree<T>
{
public:
    typedef typename Tree<T>::Node Node;
    typedef BTreeNode<T> BNode;
public:
    bool insert(Node* node) //插入結點
    {
        bool ret = true;
        return ret;
    }

    bool insert(const T& value, Node* parent)
    {
        bool ret = true;
        return ret;
    }

    //刪除節點(注意,返回被刪除的子樹!)
    SharedPointer<Tree<T> > remove(const T& value)  //刪除結點
    {
        return NULL;
    }

    SharedPointer<Tree<T> > remove(Node* node)
    {
        return NULL;
    }

    BNode* find(const T& value) const //查找節點
    {
        return NULL;
    }

    BNode* find(Node* node) const
    {
        return NULL;
    }

    BNode* root() const //獲取根結點
    {
        return this->m_root;
    }

    int degree() const  //樹的度
    {
        return 0;
    }

    int count() const  //樹的結點數目
    {
        return 0;
    }

    int height() const //樹的高度
    {
        return 0;
    }

    void clear()      //清空樹
    {
        this->m_root = NULL;
    }

    ~BTree()
    {
        clear();
    }
};



}

#endif // _BTREE_H_
相關文章
相關標籤/搜索