首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为二叉树设计通用节点?

如何为二叉树设计通用节点?
EN

Stack Overflow用户
提问于 2017-05-09 13:27:30
回答 2查看 766关注 0票数 2

我的设计问题是,我试图编写一个适合几个可能的子类型的通用类。具体来说,我试图为二进制搜索树编写一个Node类,这将适合几个搜索树的实现(Avl树、2-3树、红黑树等)。我的问题是:为了保持效率,不同的树需要Node类中的不同变量。AvlTree需要一个高度变量,RedBlackTree需要一个颜色变量( AvlTree没有使用),依此类推。什么是最好的设计解决方案:

  1. 声明节点中的许多变量(颜色、高度、平衡因子、.),并给出许多构造函数?
  2. 在Node中有一个类型为Object的变量,称为元数据,每个实现都将使用该变量来包含其元数据?
  3. 还有别的吗?
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-10 04:19:20

如何为二叉树设计通用节点?

好吧你问..。

首先,这是下面的一个很好的链接。肯定会暴露

你问题的广度,严格遵守数据结构。

等级制度让一切变得容易多了。至少你是在朝正确的方向思考。正如我在这里提到的,至少从表面上看,最好的方法(语言不可知论)在OOP中总是一样的。

顺便说一句,Java是一种优秀的语言,可以开始执行OOP原则。事实上,我刚删除了那一段..。

IFace,IFaces,FullInterface.构建任何好的抽象层次结构的秘诀是“基本的”实现。(我不会在这里实现泛型,但是Java对此提供了健壮的支持。java.util.collection,这是集合层次结构的根)。

但是,泛型实际上是为您构建的语言。在Java中,一切都是一个对象。在这里,您可以看到任何类型的go...The最抽象的表示。

对于您的具体需求:在pseudo...or中,伪伪是我所能掌握的全部内容。假冒伪劣(随便什么)。

INode必须至少有:

  1. 一个私有数据成员或密钥。
  2. 引用至少,但在这一点上,不超过2.子INode(这里有点不便)。java不允许用户通过指针直接访问内存,比如C/C++) --显然,这正是2,但在考虑渐进实现时,'AT‘至少是一个非常重要的方法。只是绝对的本质,再也没有了。
  3. 私有数据的公共访问器和变送器。
  4. 经理函数声明。(短列表,我不记得了。) 在java中是否支持操作符重载)无法想象在给定case...hmmm的情况下如何处理op相等
  5. 因为INode除了其数据之外是无用的(而不是完全发布的)。 结构,这就是我设置私有访问密钥的地方。(Java特定的)这也意味着,在引用上面的Manager函数时,INode将不会声明一个公共CTOR。Java版本的C++朋友类(ITree)。(查找类访问键/ITree)。这也显示了Singleton模式的属性。-停在这里,这个虽然看起来非常不完整,但它是抽象INode层次结构的第一阶段实现。

对于二叉树数据结构来说,这已经足够了。

(扩展或实现)具体二叉树节点类的INode接口。到目前为止很简单。

接下来,我们要寻找的设计条款将满足

一个BST节点类。这是可以想象的,虽然既不方便也不方便。

正确地,将我们当前的INode接口实现为

二进制搜索树节点类.(no...modifications!!)

它是.‘封闭的修改&&开放的扩展;

我们将从我们的新接口扩展IOrderedNode INode.我想我会把它称为接口,应该总是具有更高的描述性

命名惯例。(我知道我发生了什么事)。实际上,它

是否反映了二叉树和

二进制搜索树。二进制搜索树只是一个有序的

二叉树.显然,这是有意义的。

微不足道的,不同的。主要是,所有的实用性

串行数据结构这意味着,我们应该回到INode

和评估(不改变!)私有数据成员。

希望我们在考虑抽象扩展性时考虑周到。

那个数据成员。如果我没记错的话,java中的泛型

多功能增强.我把这个留给你。借用一个概念

在C++中,我会使用一个指向模板Arg类型的泛型指针。或

更好的是,一个空指针(不能在那里使用星号,因为它格式化我的文本)不会变得更抽象!

暂时忘记您正在使用java,因为java中的所有类型都是

整型,通过从对象类的散列代码继承

ToString()方法用户定义类型(UDT)应该在这里得到很好的考虑,因为跨数据结构的实现是完全不同的。

将实现一系列IFace扩展。(指针、引用:在java中)始终是基本级别上最好的初始类型。他们可以是

适用于指向或保持对最复杂的UDT的引用。

好的,回到我们将要利用的Serial属性。

Traversals::Pre-Order,In-Order,Post,Breadth-First.由于我们只是在探索INode层次结构,所以我们应该开始考虑将在

关联的数据结构,并尝试识别任何下属。

需要出现在我们的IOrderedNode中的依赖项

代码语言:javascript
运行
复制
//I think from here on out I will just write the code...
//20 min later...this stupid @$$ message box is the worst
//dev environment I have EVER! worked in...
//......(granted it isn't that)
//40 min later in Visual Studio. Tired of working without
//a net...no KB short cts...NO TAB! no auto formatting...?

template<class T>
class IcanOnlyBeaBT;//fwd _decl 
                //or a doubley linked list, an Adapter, a...
                //keep thinking as you go...
template<class T>
class INode
{   
    friend class IcanOnlyBeaBT<T>;//this takes care of access
public:

//  At this level we have protected
//  access for derived classes--
//  EXCEPT! with TEMPLATED classes!
//  in C++ this is NOT an issue WHEN.
//  1. data members are 'captured' by
//     template instantiation
//  2. and 3. are the exact same answer
//     as 1. only I would be forced to
//     elaborate on two specific instances
//     with the only advantage being a 
//     sufficing ward on those nit-pickers
//     who love to leave comments like
//
//          "Weellll...NOT exactly"
//
//          I dont care. I would rather
//          write my explaination for not 
//          explaining further...

        /************************************/
        // (no worries here in java - C#)
        // implement now to enforce the
        // design on higher level abstractions;
        // protected access may become 
        // private in remote derived classes
        // we never want to come back here!!!
        // push dependencies up! up! up!


     INode() : whatever_Data_I_want_Ha_Ha(nullptr) {}
     virtual void SetWhatEverDataIWant(T*) = 0;
     virtual T* GetWhateverDataIWant() = 0;
     virtual T* GetWhateverDataIWant() const = 0;
 protected:
     virtual ~INode() = 0;
     T* whatever_Data_I_want_Ha_Ha;
     INode<T>*left_child;
     INode<T>*right_child;
 };

 template<class T>
 INode<T>::~INode() {} // don't worry about this it's cool
                      //...notice that   
                  // the member is protected...and pure virtual...
                  // it's just a boomerang--    

    // Notice how adaptable this Interface has become
    // after only one extension and implementation is refined. 

    // This is BOTTOM UP because we are BUILDING... 
    // ...this should be TOP DOWN as we DESIGN...
    // THINK--TOP DOWN...BUILD BOTTOM UP...

    // Push ALL negotiable DEPENDENCIES UP AS YOU BUILD.
    // Ideally, these were identified during design.
    // It rarely ever goes that way cleanly...
    // at least not for me, but try...try

    // As incremental implementation progresses, You
    // may start to identify some of these negotiable
    // dependencies...these two interfaces are still
    // super lean..and rather boring, but continue towards
    // the AVL, Red Black, Other Data structurs they will show.

    // Nodes are, for the most part, like a drawer full
    // of silverware. They CAN'T do anything unless
    // they are being used.

    // GO UP now!!!...BUT always JUST enough!!
    // No more; GOAL...to have a DESIGN SPECIFIC
    // hierarchy, that IS extensible in a MODULAR 
    // fasion, like LEGOS. ADAPTABLE to ANY COMPATIBLE
    // Data Structure, Not just TREES. Even from here...
    // there are other suitablilities coming to mind,
    // such as Graphs, Doubley Linked Lists, circular queues.
    // Nodes are common place in Data Structures...on...on...

    // Principle Attribute: ICanBe_A_BST Data Struct now.

    // fwd _decl: 
  template<class T>     
  class ICanBe_A_BST; //The BT Node was FIRST Abstraction, 
                // BST is SECOND.
                // OR a Composite Object Structure! for the  
                // Composite Design Pattern...or...or...or
                // BECAUSE, this IOrderedNode is more QUALIFIED 
                // and adaptable. LOOK HERE! Don't throw away
                // the specific sutibility of lower abstractions
                // This should be extended to fulfil design reqs
                // IOrderedNode is not intended to be a BT, 
                // IT 'IS A' BT by extension, BUT, it is a BST Node.

                // This abstract hierarchy, UPON DESIGN COMPLETION  
                // Will have pervasive extensibility @ unique levels.  
                // think {OPEN-CLOSED} open for EXTENSION, and
                // CLOSED for MODIFICATION...GOAL...DON'T...come
                // BACK inside this BLACK BOX once it is CLOSED..!  

template<class T>
class IOrderedNode : public INode<T>
{ 
              // RIGHT HERE! ALL previous implementation
              // Is abstracted AWAY. Look how clean it all is..
              // in java you would be Extending INode Interface HERE!.
              // Extending IN JAVA IS inheritance.
              // ALL public and protected members.
              // Closed for MOD. open for EXTENSION
public:                                
    IOrderedNode() : height(0) { }

protected:
//NOTICE!(I Can Be A BST Node IF!)my data is INTEGRAL & comparable.
//FOR instance a bool is unqualified--how can you order a tree
//when the only value is a 1 or a 0;
//UDT is dependent upon guess...
//THE USER who defind it(integral && comparable);

// Question: is there anything missing from this level 
// that would disqualify concrete instantiations from adequately
// filling the intended role? .....Seriously...
// I have been awake for two days now. This may need editing. 
// Regardless the process is the 
// same all the way to Red Black and beyond...

int height; //new data member; height of the tree at that node...
            //this comes in handy when computing the balance factor
            //on balanced trees...AVL, R&B,
};



/***********************NOTE:***********************
*
*   There are several considerations that have to be made 
*   when you are "leaving" data and and implementation "behind". 
*   We know we don't EVER want to come back here...
    (not a super realistic GOAL...)
*   Is the implementation specific to the level of bstraction.?...
*   YES? then leave it here. 

    IS...the DATA specific to the implementation ????
*   this deserves 4 Q-marks because, IF at all POSSIBLE PUSH
*   these IMPLEMENTATION DEPENDENCIES..UP This RESULTS in IoC
*   Inversion of Control Inversion of CONTROL INVERSION! of Control...
*   Implementation dependencies should come from higher level abs
*   to lower level Implementation...repeats you are seeing all over
    this now TLDR, are Cardinal principles of Object
*   Oriented Design. Not because I love commenting code...
    but since YOU asked...I won't leave out the 'life blood'.

*   Incidentally, there is a requisite 
    'AHAAH moment' that either comes
*       or it doesn't.
*
****************************   PERSONAL NOTE:*********************
*
*   I picked up java in the late 90's, and was like.
*   "...what the hell is an OBJECT..?" Two years of programming from a
*   procedural paradigm, in an OOP language-LATER! It hit me......
*   (I know...slow learner)...but I remember saying out loud....
*   'THAT...IS...THE...COOLEST...THING...I HAVE EVER...tripped over...
*   Consensually, OOP is considered to be in its INFANCY. 
*   Theories (opinions) are often the cause of some rather heated
*   contest. In fact, one of the most intense and persistant 
    "cival-war" I have ever encountered, nearly dominated an entire 
    forum. I didn't really know enough to have an opinion
*   one way or the other on the matter, but I remember thinking, 
    how absurd...and laughing alot.
*   The theoretical epicenter was localized on the issue of...
        wait for it...
*
*                   INHERITANCE v.s. COMPOSITION/AGGRAGATION
*
*       Hmm....Everybody knows that programming to interfaces, 
    adhereing to common sense, established design principles, 
    and proven patterns, can all be accomplished without inheriting
    from a single archtype...
*        "Not that there's anything wrong with that..." 
    I'm pretty sure, that was the vein of the row on that
         forum...Super entertaining though...
*
*******************************************/
票数 1
EN

Stack Overflow用户

发布于 2018-08-01 19:06:10

我也有同样的问题,决定采用这个简单的解决方案。

代码语言:javascript
运行
复制
abstract class BSTnode<K, M> {
    K key;
    M meta; 
    BSTnode<K> left;
    BSTnode<K> right;
    BSTnode<K> parent;
}

这简单地解决了元数据的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43871199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档