OOP:设计一个树,在Node类和tree类之间划分功能

OOP: Designing a tree, dividing functionality between Node class and a Tree Class

本文关键字:类和 Node tree 功能 划分 之间 一个 OOP      更新时间:2023-10-16

我需要实现一个自定义树类(使用C++)。在我的整个工作中,我看到了许多树的实现。有些实现了一个向用户公开的"超级节点"类。其(根节点)充当树的实例。有些公开了一个树类,它利用一个节点类来构造一个树。有些将节点类用作纯数据结构,将树构造等功能留给树类。另一些人则把这个节点比作建筑。Split(),到节点类中。

假设您需要设计一个二进制树(如KD树)。从OOP的角度来看,什么是"最好的"方法。节点类是否只包含数据,或者包含将自身拆分为子级的逻辑?一个节点类通常应该包含多少逻辑?

感谢您的建设性意见!

这里有一条OOP规则你应该始终遵循,

每个类都代表一个实体。类具有属性和方法即实体的属性及其行为

因此,你需要遵循你对场景的理解。

以下是我对节点的看法。它有一些数据,一个右节点引用和一个左节点引用。我不认为一个节点应该能够做任何事情,除了向您提供数据,所以我会写一个节点类,比如:

class Node
{
public:
    int Data;    // yeah, you would obviously use templates, so it's not restricted to a particular type
    Node* Left;
    Node* Right;
    // also you can write constructors and maybe some sort of cast operator overload to be able to make the 
    // we could also make it return the subtree itself
    getRightSubTree(){ return Tree(*Right); }
    getLeftSubTree(){ return Tree(*Left); }
};

那么一棵树应该是这样的。

class Tree
{
private:
    Node root;
public:
    Tree(Node t):root(t){} // every tree should have a root. Cannot be null.
    // since the root node will be able to handle the tree structure, now we'll need the necessary methods
    void addNode(Node n){
    // code here
    }
    ....

    getSubTree(int data){
        // check if node with that data exists and all
        ...
        Node n = getNode(data);
        return Tree(n);
    }
};

好吧,我想你现在有个主意了。这一切都是关于你如何看待这个系统。