unit BtreeNC;
//*******************************************************
// B-tree node class.
//*******************************************************
// Copyright (C) 1998 John Wiley & Sons, Inc.
// All rights reserved. See additional copyright
// information in Readme.txt.
//*******************************************************

interface

uses
    Windows, Graphics, Math, SysUtils;

const
    ORDER = 2;                 // The tree's order.
    KEYS_PER_NODE = 2 * ORDER; // Max keys per node.

type
    TBalance = (LeftHeavy, Balanced, RightHeavy);
    TBtreeNode = class(TObject)
        private
        public
            NumKeys  : Integer;   // Keys in use.
            Key      : array [1..KEYS_PER_NODE] of Integer;
            Child    : array [0..KEYS_PER_NODE] of TBtreeNode;

            constructor Create;
            destructor Destroy; override;
            class function NumAllocated : Integer;
            function TextValue(spaces : Integer) : String;
    end;

implementation

const
    WID = 40;
    HGT = 16;
    HGAP = 2;
    VGAP = 6;

var
    NodesAllocated : Integer;

// Keep count of nodes allocated.
constructor TBtreeNode.Create;
begin
    NodesAllocated := NodesAllocated + 1;
    inherited Create;
end;

// Free any children.
destructor TBtreeNode.Destroy;
var
    i : Integer;
begin
    NodesAllocated := NodesAllocated - 1;

    // Free any children.
    for i := 0 to NumKeys do Child[i].Free;
    inherited Destroy;
end;

// Return the number of nodes currently allocated.
class function TBtreeNode.NumAllocated : Integer;
begin
    Result := NodesAllocated;
end;

// Return a textual representation of the subtree
// beneath this node.
function TBtreeNode.TextValue(spaces : Integer) : String;
const
    CR = #13#10;
var
    i : Integer;
begin
    Result := '';
    if (Child[0] <> nil) then
        Result := Result +
            Child[0].TextValue(spaces + 2);

    for i := 1 to NumKeys do
    begin
        Result := Result + Format('%*s', [spaces, '']) +
            IntToStr(Key[i]) + CR;
        if (Child[i] <> nil) then
            Result := Result +
                Child[i].TextValue(spaces + 2);
    end;
end;

end.
