Tuesday, October 26, 2010

Generic Tree

Looks like today is the generic collection day, now is time for a generic tree, it is located in BB.Collection.Tree.Generic.

Tree are a very fast way of insert, add, delete and search, but for linear access is slow (or at least not as fast as other types), for pure maintenance is the best structure, but not the best for specific task (only add or only delete, etc)

It looks like this:


type
  TNode<T> = class
  private
    FLeft: TNode<T>;
    FParent: TNode<T>;
    FRight: TNode<T>;
    FData: T;
  public
    constructor Create; virtual;

    property Parent: TNode<T> Read FParent Write FParent;
    property Left: TNode<T> Read FLeft Write FLeft;
    property Right: TNode<T> Read FRight Write FRight;
    property Data: T Read FData Write FData;
  end;

  TTree<T> = class(TVar, ICollection<T>)
  private
    FRoot,
    FCurrent: TNode<T>;
    FCount: integer;
    FOwnObjects: boolean;
    FDuplicates: boolean;
    FPool: TObjectPool;
    FComparer: IEqualityComparer<T>;

    function Get(aIndex: integer): T;
    procedure Put(aIndex: integer; aObject: T);
    function GetCount: integer;
    function FirstItem: T;
    function NextItem: T;
    function PriorItem: T;
    function LastItem: T;
    procedure AddNode(var aNode: TNode<T>; aParent: TNode<T>; aObject: T; aCmp: IComparable);
    procedure TryFreeObject(aItem: T);
  public
    constructor Create; override;
    destructor Destroy; override;
    function IndexOf(aObject: T): integer;
    function Add(aObject: T): integer;  
    procedure Delete(aObject: T);
    procedure Clear(aExcept: T); reintroduce; overload;
    procedure Clear; overload; override;
    function Extract(aObject: T): T;
    procedure Insert(aObject: T; aWhere: integer); virtual;
    function Clone: TObject; override;
    //IIterator
    function First: boolean;
    function Last: boolean;
    function Next: boolean;
    function GetCurrent: T;

    property Count: integer read GetCount;
    property Current: TNode<T> Read FCurrent;
    property Items[index: integer]: T Read Get Write Put; default;
    property OwnObjects: boolean Read FOwnObjects Write FOwnObjects;
    property Duplicates: boolean Read FDuplicates Write FDuplicates;
  end;
We have typical iterators and maintenance

1 comment: