From 4f6da03e178260a6d55b2f34e93f6577ed9e0c8c Mon Sep 17 00:00:00 2001 From: skamradt Date: Thu, 21 Mar 2024 13:55:20 -0500 Subject: [PATCH] Added method Root that returns the root by walking the parent chain upwards Added method Depth that returns the depth of the current node from the root --- TeeGenericTree.pas | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/TeeGenericTree.pas b/TeeGenericTree.pas index d9b248a..d9b3b0d 100644 --- a/TeeGenericTree.pas +++ b/TeeGenericTree.pas @@ -156,6 +156,8 @@ TNode=class procedure Delete(const Index:TInteger; const ACount:TInteger=1); procedure ForEach(const AProc:TNodeProc; const Recursive:Boolean=True); procedure Sort(const ACompare:TCompareProc; const Recursive:Boolean=True); + function Root : TNode; + function Depth : integer; property Index:TInteger read GetIndex; property Item[const Index:TInteger]:TNode read Get; default; @@ -172,6 +174,7 @@ implementation Constructor TNode.Create(const AData: T); begin inherited Create; + fParent := nil; Data:=AData; end; @@ -241,6 +244,19 @@ procedure TNode.Delete(const Index, ACount: TInteger); Extract(Index,ACount); end; +function TNode.Depth: integer; +var + tmp : TNode; +begin + Result := 0; + Tmp := self; + while assigned(tmp.Parent) do + begin + inc(Result); + tmp := tmp.Parent; + end; +end; + // Returns True when this node has no children nodes function TNode.Empty:Boolean; begin @@ -385,6 +401,13 @@ procedure TNode.PrivateSort(const ACompare: TCompareProc; const l,r:TInteger) PrivateSort(ACompare,i,r); end; +function TNode.Root: TNode; +begin + Result := Self; // default we are the root + While Assigned(Result.Parent) do + Result := Result.Parent; +end; + // Re-order children items according to a custom ACompare function procedure TNode.Sort(const ACompare: TCompareProc; const Recursive: Boolean); var t : TInteger;