1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
|
{ **********************************************************************
This file is part of the Free Component Library (FCL)
Copyright (c) 2017 by Mattias Gaertner
Average Level Tree implementation by Mattias Gaertner
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**********************************************************************
Author: Mattias Gaertner
Abstract:
TAVLTree is an Average Level binary Tree. This binary tree is always
balanced, so that inserting, deleting and finding a node is performed in
O(log(#Nodes)).
Note! This is a copy of avl_tree unit from FPC 3.1.1 from 6th Apr 2017.
Can be removed when FPC 3.2 is the minimun requirement for Lazarus and LazUtils.
}
unit Laz_AVL_Tree;
{$ifdef FPC}{$mode objfpc}{$endif}{$H+}
interface
{off $DEFINE MEM_CHECK}
{off $DEFINE CheckAVLTreeNodeManager}
uses
{$IFDEF MEM_CHECK}MemCheck,{$ENDIF}
Classes, SysUtils;
type
TAVLTree = class;
TObjectSortCompare = function(Tree: TAVLTree; Data1, Data2: Pointer): integer of object;
{ TAVLTreeNode }
TAVLTreeNode = class
public
Parent, Left, Right: TAVLTreeNode;
Balance: integer; // = RightDepth-LeftDepth -2..+2, after balancing: -1,0,+1
Data: Pointer;
function Successor: TAVLTreeNode; // next right
function Precessor: TAVLTreeNode; // next left
procedure Clear;
function TreeDepth: integer; // longest WAY down. e.g. only one node => 0 !
procedure ConsistencyCheck(Tree: TAVLTree); virtual;
function GetCount: SizeInt;
end;
TAVLTreeNodeClass = class of TAVLTreeNode;
PAVLTreeNode = ^TAVLTreeNode;
{ TBaseAVLTreeNodeManager }
TBaseAVLTreeNodeManager = class
public
procedure DisposeNode(ANode: TAVLTreeNode); virtual; abstract;
function NewNode: TAVLTreeNode; virtual; abstract;
end;
{ TAVLTreeNodeEnumerator }
TAVLTreeNodeEnumerator = class
protected
FCurrent: TAVLTreeNode;
FLowToHigh: boolean;
FTree: TAVLTree;
public
constructor Create(Tree: TAVLTree; aLowToHigh: boolean = true);
function GetEnumerator: TAVLTreeNodeEnumerator; inline;
function MoveNext: Boolean;
property Current: TAVLTreeNode read FCurrent;
property LowToHigh: boolean read FLowToHigh;
end;
TAVLTree = class
protected
FCount: SizeInt;
FNodeClass: TAVLTreeNodeClass;
fNodeMgr: TBaseAVLTreeNodeManager;
fNodeMgrAutoFree: boolean;
FOnCompare: TListSortCompare;
FOnObjectCompare: TObjectSortCompare;
FRoot: TAVLTreeNode;
procedure BalanceAfterInsert(ANode: TAVLTreeNode);
procedure BalanceAfterDelete(ANode: TAVLTreeNode);
procedure DeletingNode({%H-}aNode: TAVLTreeNode); virtual;
function FindInsertPos(Data: Pointer): TAVLTreeNode;
procedure Init; virtual;
procedure NodeAdded({%H-}aNode: TAVLTreeNode); virtual;
procedure RotateLeft(aNode: TAVLTreeNode); virtual;
procedure RotateRight(aNode: TAVLTreeNode); virtual;
procedure SwitchPositionWithSuccessor(aNode, aSuccessor: TAVLTreeNode); virtual;
procedure SetOnCompare(const AValue: TListSortCompare);
procedure SetOnObjectCompare(const AValue: TObjectSortCompare);
procedure SetCompares(const NewCompare: TListSortCompare;
const NewObjectCompare: TObjectSortCompare);
procedure SetNodeClass(const AValue: TAVLTreeNodeClass);
public
constructor Create(const OnCompareMethod: TListSortCompare);
constructor CreateObjectCompare(const OnCompareMethod: TObjectSortCompare);
constructor Create;
destructor Destroy; override;
property OnCompare: TListSortCompare read FOnCompare write SetOnCompare;
property OnObjectCompare: TObjectSortCompare read FOnObjectCompare write SetOnObjectCompare;
property NodeClass: TAVLTreeNodeClass read FNodeClass write SetNodeClass; // used for new nodes
procedure SetNodeManager(NewMgr: TBaseAVLTreeNodeManager;
AutoFree: boolean = false);
function NewNode: TAVLTreeNode; virtual; // create a node outside the tree
procedure DisposeNode(ANode: TAVLTreeNode); virtual; // free the node outside the tree
// add, delete, remove, move
procedure Add(ANode: TAVLTreeNode);
function Add(Data: Pointer): TAVLTreeNode;
function AddAscendingSequence(Data: Pointer; LastAdded: TAVLTreeNode;
var Successor: TAVLTreeNode): TAVLTreeNode;
procedure Delete(ANode: TAVLTreeNode);
// JuMa: Turned Remove and RemovePointer into functions.
function Remove(Data: Pointer): boolean;
function RemovePointer(Data: Pointer): boolean;
procedure MoveDataLeftMost(var ANode: TAVLTreeNode);
procedure MoveDataRightMost(var ANode: TAVLTreeNode);
procedure Clear;
procedure FreeAndClear;
procedure FreeAndDelete(ANode: TAVLTreeNode); virtual;
function Equals(Obj: TObject): boolean; override; // same as IsEqual(aTree,false)
function IsEqual(aTree: TAVLTree; CheckDataPointer: boolean): boolean; // checks only keys or Data (references), not the data itself, O(n)
procedure Assign(aTree: TAVLTree); virtual; // clear and copy all Data (references), O(n)
// search
property Root: TAVLTreeNode read fRoot;
property Count: SizeInt read FCount;
function Compare(Data1, Data2: Pointer): integer;
function Find(Data: Pointer): TAVLTreeNode; // O(log(n))
function FindKey(Key: Pointer;
const OnCompareKeyWithData: TListSortCompare): TAVLTreeNode; // O(log(n))
function FindNearestKey(Key: Pointer;
const OnCompareKeyWithData: TListSortCompare): TAVLTreeNode; // O(log(n))
function FindSuccessor(ANode: TAVLTreeNode): TAVLTreeNode; inline;
function FindPrecessor(ANode: TAVLTreeNode): TAVLTreeNode; inline;
function FindLowest: TAVLTreeNode; // O(log(n))
function FindHighest: TAVLTreeNode; // O(log(n))
function FindNearest(Data: Pointer): TAVLTreeNode;
// search in a tree with duplicates (duplicate means here: Compare function returns 0)
function FindPointer(Data: Pointer): TAVLTreeNode;
function FindLeftMost(Data: Pointer): TAVLTreeNode;
function FindRightMost(Data: Pointer): TAVLTreeNode;
function FindLeftMostKey(Key: Pointer;
const OnCompareKeyWithData: TListSortCompare): TAVLTreeNode;
function FindRightMostKey(Key: Pointer;
const OnCompareKeyWithData: TListSortCompare): TAVLTreeNode;
function FindLeftMostSameKey(ANode: TAVLTreeNode): TAVLTreeNode;
function FindRightMostSameKey(ANode: TAVLTreeNode): TAVLTreeNode;
// enumerators
function GetEnumerator: TAVLTreeNodeEnumerator;
function GetEnumeratorHighToLow: TAVLTreeNodeEnumerator;
// consistency
procedure ConsistencyCheck; virtual; // JuMa: changed to procedure and added "virtual".
procedure WriteReportToStream(s: TStream);
function NodeToReportStr(aNode: TAVLTreeNode): string; virtual;
function ReportAsString: string;
end;
TAVLTreeClass = class of TAVLTree;
{ TAVLTreeNodeMemManager }
TAVLTreeNodeMemManager = class(TBaseAVLTreeNodeManager)
private
FFirstFree: TAVLTreeNode;
FFreeCount: SizeInt;
FCount: SizeInt;
FMinFree: SizeInt;
FMaxFreeRatio: SizeInt;
{$IFDEF CheckAVLTreeNodeManager}
FThreadId: TThreadID;
{$ENDIF}
procedure SetMaxFreeRatio(NewValue: SizeInt);
procedure SetMinFree(NewValue: SizeInt);
procedure DisposeFirstFreeNode;
public
procedure DisposeNode(ANode: TAVLTreeNode); override;
function NewNode: TAVLTreeNode; override;
property MinimumFreeNode: SizeInt read FMinFree write SetMinFree;
property MaximumFreeNodeRatio: SizeInt
read FMaxFreeRatio write SetMaxFreeRatio; // in one eighth steps
property Count: SizeInt read FCount;
procedure Clear;
constructor Create;
destructor Destroy; override;
end;
var
LazNodeMemManager: TAVLTreeNodeMemManager;
implementation
function ComparePointer(Data1, Data2: Pointer): integer;
begin
if Data1>Data2 then Result:=-1
else if Data1<Data2 then Result:=1
else Result:=0;
end;
{ TAVLTreeNodeEnumerator }
constructor TAVLTreeNodeEnumerator.Create(Tree: TAVLTree; aLowToHigh: boolean);
begin
FTree:=Tree;
FLowToHigh:=aLowToHigh;
end;
function TAVLTreeNodeEnumerator.GetEnumerator: TAVLTreeNodeEnumerator;
begin
Result:=Self;
end;
function TAVLTreeNodeEnumerator.MoveNext: Boolean;
begin
if FLowToHigh then begin
if FCurrent<>nil then
FCurrent:=FCurrent.Successor
else
FCurrent:=FTree.FindLowest;
end else begin
if FCurrent<>nil then
FCurrent:=FCurrent.Precessor
else
FCurrent:=FTree.FindHighest;
end;
Result:=FCurrent<>nil;
end;
{ TAVLTree }
function TAVLTree.Add(Data: Pointer): TAVLTreeNode;
begin
Result:=NewNode;
Result.Data:=Data;
Add(Result);
end;
function TAVLTree.AddAscendingSequence(Data: Pointer; LastAdded: TAVLTreeNode;
var Successor: TAVLTreeNode): TAVLTreeNode;
{ This is an optimized version of "Add" for adding an ascending sequence of
nodes.
It uses the LastAdded and Successor to skip searching for an insert position.
For nodes with same value the order of the sequence is kept.
Usage:
LastNode:=nil; // TAvlTreeNode
Successor:=nil; // TAvlTreeNode
for i:=1 to 1000 do
LastNode:=Tree.AddAscendingSequence(TItem.Create(i),LastNode,Successor);
}
var
InsertPos: TAVLTreeNode;
begin
Result:=NewNode;
Result.Data:=Data;
if (LastAdded<>nil) and (Compare(LastAdded.Data,Data)<=0)
and ((Successor=nil) or (Compare(Data,Successor.Data)<=0)) then begin
// Data is between LastAdded and Successor
inc(FCount);
if LastAdded.Right=nil then begin
Result.Parent:=LastAdded;
LastAdded.Right:=Result;
end else begin
InsertPos:=LastAdded.Right;
while InsertPos.Left<>nil do
InsertPos:=InsertPos.Left;
Result.Parent:=InsertPos;
InsertPos.Left:=Result;
end;
NodeAdded(Result);
BalanceAfterInsert(Result);
end else begin
// normal Add
Add(Result);
Successor:=Result.Successor;
end;
end;
function TAVLTree.NewNode: TAVLTreeNode;
begin
if fNodeMgr<>nil then
Result:=fNodeMgr.NewNode
else
Result:=NodeClass.Create;
end;
procedure TAVLTree.DisposeNode(ANode: TAVLTreeNode);
begin
if fNodeMgr<>nil then
fNodeMgr.DisposeNode(ANode)
else
ANode.Free;
end;
procedure TAVLTree.Add(ANode: TAVLTreeNode);
// add a node. If there are already nodes with the same value it will be
// inserted rightmost
var InsertPos: TAVLTreeNode;
InsertComp: integer;
begin
ANode.Left:=nil;
ANode.Right:=nil;
inc(FCount);
if Root<>nil then begin
InsertPos:=FindInsertPos(ANode.Data);
InsertComp:=Compare(ANode.Data,InsertPos.Data);
ANode.Parent:=InsertPos;
if InsertComp<0 then begin
// insert to the left
InsertPos.Left:=ANode;
end else begin
// insert to the right
InsertPos.Right:=ANode;
end;
NodeAdded(ANode);
BalanceAfterInsert(ANode);
end else begin
fRoot:=ANode;
ANode.Parent:=nil;
NodeAdded(ANode);
end;
end;
function TAVLTree.FindLowest: TAVLTreeNode;
begin
Result:=Root;
if Result<>nil then
while Result.Left<>nil do Result:=Result.Left;
end;
function TAVLTree.FindHighest: TAVLTreeNode;
begin
Result:=Root;
if Result<>nil then
while Result.Right<>nil do Result:=Result.Right;
end;
procedure TAVLTree.BalanceAfterDelete(ANode: TAVLTreeNode);
var
OldParent, OldRight, OldRightLeft, OldLeft, OldLeftRight: TAVLTreeNode;
begin
while ANode<>nil do begin
if ((ANode.Balance=+1) or (ANode.Balance=-1)) then exit;
OldParent:=ANode.Parent;
if (ANode.Balance=0) then begin
// Treeheight has decreased by one
if (OldParent=nil) then
exit;
if(OldParent.Left=ANode) then
Inc(OldParent.Balance)
else
Dec(OldParent.Balance);
ANode:=OldParent;
end else if (ANode.Balance=+2) then begin
// Node is overweighted to the right
OldRight:=ANode.Right;
if (OldRight.Balance>=0) then begin
// OldRight.Balance is 0 or -1
// rotate ANode,OldRight left
RotateLeft(ANode);
ANode.Balance:=(1-OldRight.Balance); // toggle 0 and 1
Dec(OldRight.Balance);
ANode:=OldRight;
end else begin
// OldRight.Balance=-1
{ double rotate
= rotate OldRightLeft,OldRight right
and then rotate ANode,OldRightLeft left
OldParent OldParent
| |
ANode OldRightLeft
\ / \
OldRight => ANode OldRight
/ \ /
OldRightLeft OldRightLeftLeft OldRightLeftRight
/ \
OldRightLeftLeft OldRightLeftRight
}
OldRightLeft:=OldRight.Left;
RotateRight(OldRight);
RotateLeft(ANode);
if (OldRightLeft.Balance<=0) then
ANode.Balance:=0
else
ANode.Balance:=-1;
if (OldRightLeft.Balance>=0) then
OldRight.Balance:=0
else
OldRight.Balance:=+1;
OldRightLeft.Balance:=0;
ANode:=OldRightLeft;
end;
end else begin
// Node.Balance=-2
// Node is overweighted to the left
OldLeft:=ANode.Left;
if (OldLeft.Balance<=0) then begin
// rotate OldLeft,ANode right
RotateRight(ANode);
ANode.Balance:=(-1-OldLeft.Balance); // toggle 0 and -1
Inc(OldLeft.Balance);
ANode:=OldLeft;
end else begin
// OldLeft.Balance = 1
{ double rotate left right
= rotate OldLeft,OldLeftRight left
and then rotate OldLeft,ANode right
OldParent OldParent
| |
ANode OldLeftRight
/ / \
OldLeft => OldLeft ANode
\ \ /
OldLeftRight OldLeftRightLeft OldLeftRightRight
/ \
OldLeftRightLeft OldLeftRightRight
}
OldLeftRight:=OldLeft.Right;
RotateLeft(OldLeft);
RotateRight(ANode);
if (OldLeftRight.Balance>=0) then
ANode.Balance:=0
else
ANode.Balance:=+1;
if (OldLeftRight.Balance<=0) then
OldLeft.Balance:=0
else
OldLeft.Balance:=-1;
OldLeftRight.Balance:=0;
ANode:=OldLeftRight;
end;
end;
end;
end;
procedure TAVLTree.DeletingNode(aNode: TAVLTreeNode);
// called by Delete
// Node.Left=nil or Node.Right=nil
begin
// for descendants to override
end;
procedure TAVLTree.SetOnObjectCompare(const AValue: TObjectSortCompare);
begin
if AValue=nil then
SetCompares(FOnCompare,nil)
else
SetCompares(nil,AValue);
end;
procedure TAVLTree.SetCompares(const NewCompare: TListSortCompare;
const NewObjectCompare: TObjectSortCompare);
var List: PPointer;
ANode: TAVLTreeNode;
i, OldCount: integer;
begin
if (FOnCompare=NewCompare) and (FOnObjectCompare=NewObjectCompare) then exit;
if Count<=1 then begin
FOnCompare:=NewCompare;
FOnObjectCompare:=NewObjectCompare;
exit;
end;
// sort the tree again
OldCount:=Count;
GetMem(List,SizeOf(Pointer)*OldCount);
try
// save the data in a list
ANode:=FindLowest;
i:=0;
while ANode<>nil do begin
List[i]:=ANode.Data;
inc(i);
ANode:=ANode.Successor;
end;
// clear the tree
Clear;
// set the new compare function
FOnCompare:=NewCompare;
FOnObjectCompare:=NewObjectCompare;
// re-add all nodes
for i:=0 to OldCount-1 do
Add(List[i]);
finally
FreeMem(List);
end;
end;
procedure TAVLTree.SetNodeClass(const AValue: TAVLTreeNodeClass);
begin
if FNodeClass=AValue then Exit;
if Count>0 then
raise Exception.Create(ClassName+'.SetNodeClass Count='+IntToStr(Count)
+' Old='+fNodeMgr.ClassName+' New='+AValue.ClassName);
FNodeClass:=AValue;
if fNodeMgr=LazNodeMemManager then
fNodeMgr:=nil;
end;
procedure TAVLTree.BalanceAfterInsert(ANode: TAVLTreeNode);
var
OldParent, OldRight, OldLeft: TAVLTreeNode;
begin
OldParent:=ANode.Parent;
while (OldParent<>nil) do begin
if (OldParent.Left=ANode) then begin
// Node is left child
dec(OldParent.Balance);
if (OldParent.Balance=0) then exit;
if (OldParent.Balance=-1) then begin
ANode:=OldParent;
OldParent:=ANode.Parent;
continue;
end;
// OldParent.Balance=-2
if (ANode.Balance=-1) then begin
{ rotate ANode,ANode.Parent right
OldParentParent OldParentParent
| |
OldParent => ANode
/ \
ANode OldParent
\ /
OldRight OldRight }
RotateRight(OldParent);
ANode.Balance:=0;
OldParent.Balance:=0;
end else begin
// Node.Balance = +1
{ double rotate
= rotate ANode,OldRight left and then rotate OldRight,OldParent right
OldParentParent OldParentParent
| |
OldParent OldRight
/ => / \
ANode ANode OldParent
\ \ /
OldRight OldRightLeft OldRightRight
/ \
OldRightLeft OldRightRight
}
OldRight:=ANode.Right;
RotateLeft(ANode);
RotateRight(OldParent);
if (OldRight.Balance<=0) then
ANode.Balance:=0
else
ANode.Balance:=-1;
if (OldRight.Balance=-1) then
OldParent.Balance:=1
else
OldParent.Balance:=0;
OldRight.Balance:=0;
end;
exit;
end else begin
// Node is right child
Inc(OldParent.Balance);
if (OldParent.Balance=0) then exit;
if (OldParent.Balance=+1) then begin
ANode:=OldParent;
OldParent:=ANode.Parent;
continue;
end;
// OldParent.Balance = +2
if(ANode.Balance=+1) then begin
{ rotate OldParent,ANode left
OldParentParent OldParentParent
| |
OldParent => ANode
\ /
ANode OldParent
/ \
OldLeft OldLeft }
RotateLeft(OldParent);
ANode.Balance:=0;
OldParent.Balance:=0;
end else begin
// Node.Balance = -1
{ double rotate
= rotate OldLeft,ANode right and then rotate OldParent,OldLeft right
OldParentParent OldParentParent
| |
OldParent OldLeft
\ => / \
ANode OldParent ANode
/ \ /
OldLeft OldLeftLeft OldLeftRight
/ \
OldLeftLeft OldLeftRight
}
OldLeft:=ANode.Left;
RotateRight(ANode);
RotateLeft(OldParent);
if (OldLeft.Balance>=0) then
ANode.Balance:=0
else
ANode.Balance:=+1;
if (OldLeft.Balance=+1) then
OldParent.Balance:=-1
else
OldParent.Balance:=0;
OldLeft.Balance:=0;
end;
exit;
end;
end;
end;
procedure TAVLTree.Clear;
procedure DeleteNode(ANode: TAVLTreeNode);
begin
if ANode.Left<>nil then DeleteNode(ANode.Left);
if ANode.Right<>nil then DeleteNode(ANode.Right);
DisposeNode(ANode);
end;
// Clear
begin
if Root<>nil then
DeleteNode(Root);
fRoot:=nil;
FCount:=0;
end;
constructor TAVLTree.Create(const OnCompareMethod: TListSortCompare);
begin
FOnCompare:=OnCompareMethod;
Init;
end;
constructor TAVLTree.CreateObjectCompare(
const OnCompareMethod: TObjectSortCompare);
begin
FOnObjectCompare:=OnCompareMethod;
Init;
end;
constructor TAVLTree.Create;
begin
Create(@ComparePointer);
end;
procedure TAVLTree.Delete(ANode: TAVLTreeNode);
var
OldParent, Child: TAVLTreeNode;
begin
{$IFDEF CheckAVLTreeNodeManager}
OldParent:=ANode;
while OldParent.Parent<>nil do OldParent:=OldParent.Parent;
if OldParent<>Root then
raise Exception.Create('TAVLTree.Delete'); // not my node
{$ENDIF}
if (ANode.Left<>nil) and (ANode.Right<>nil) then begin
// ANode has both: Left and Right
// Switch ANode position with Successor
// Because ANode.Right<>nil the Successor is a child of ANode
SwitchPositionWithSuccessor(ANode,ANode.Successor);
end;
// left or right is nil
DeletingNode(aNode);
OldParent:=ANode.Parent;
ANode.Parent:=nil;
if ANode.Left<>nil then
Child:=ANode.Left
else
Child:=ANode.Right;
if Child<>nil then
Child.Parent:=OldParent;
if (OldParent<>nil) then begin
// Node has parent
if (OldParent.Left=ANode) then begin
// Node is left child of OldParent
OldParent.Left:=Child;
Inc(OldParent.Balance);
end else begin
// Node is right child of OldParent
OldParent.Right:=Child;
Dec(OldParent.Balance);
end;
BalanceAfterDelete(OldParent);
end else begin
// Node was Root
fRoot:=Child;
end;
dec(FCount);
DisposeNode(ANode);
end;
function TAVLTree.Remove(Data: Pointer): boolean;
var
ANode: TAvlTreeNode;
begin
ANode:=Find(Data);
if ANode<>nil then begin
Delete(ANode);
Result:=true;
end else
Result:=false;
end;
function TAVLTree.RemovePointer(Data: Pointer): boolean;
var
ANode: TAvlTreeNode;
begin
ANode:=FindPointer(Data);
if ANode<>nil then begin
Delete(ANode);
Result:=true;
end else
Result:=false;
end;
destructor TAVLTree.Destroy;
begin
Clear;
if fNodeMgrAutoFree then
FreeAndNil(fNodeMgr);
inherited Destroy;
end;
function TAVLTree.GetEnumerator: TAVLTreeNodeEnumerator;
begin
Result:=TAVLTreeNodeEnumerator.Create(Self,true);
end;
function TAVLTree.GetEnumeratorHighToLow: TAVLTreeNodeEnumerator;
begin
Result:=TAVLTreeNodeEnumerator.Create(Self,false);
end;
function TAVLTree.Find(Data: Pointer): TAVLTreeNode;
var Comp: integer;
begin
Result:=Root;
while (Result<>nil) do begin
Comp:=Compare(Data,Result.Data);
if Comp=0 then exit;
if Comp<0 then begin
Result:=Result.Left
end else begin
Result:=Result.Right
end;
end;
end;
function TAVLTree.FindKey(Key: Pointer; const OnCompareKeyWithData: TListSortCompare
): TAVLTreeNode;
var Comp: integer;
begin
Result:=Root;
while (Result<>nil) do begin
Comp:=OnCompareKeyWithData(Key,Result.Data);
if Comp=0 then exit;
if Comp<0 then begin
Result:=Result.Left
end else begin
Result:=Result.Right
end;
end;
end;
function TAVLTree.FindNearestKey(Key: Pointer;
const OnCompareKeyWithData: TListSortCompare): TAVLTreeNode;
var Comp: integer;
begin
Result:=fRoot;
while (Result<>nil) do begin
Comp:=OnCompareKeyWithData(Key,Result.Data);
if Comp=0 then exit;
if Comp<0 then begin
if Result.Left<>nil then
Result:=Result.Left
else
exit;
end else begin
if Result.Right<>nil then
Result:=Result.Right
else
exit;
end;
end;
end;
function TAVLTree.FindLeftMostKey(Key: Pointer;
const OnCompareKeyWithData: TListSortCompare): TAVLTreeNode;
var
LeftNode: TAVLTreeNode;
begin
Result:=FindKey(Key,OnCompareKeyWithData);
if Result=nil then exit;
repeat
LeftNode:=Result.Precessor;
if (LeftNode=nil) or (OnCompareKeyWithData(Key,LeftNode.Data)<>0) then exit;
Result:=LeftNode;
until false;
end;
function TAVLTree.FindRightMostKey(Key: Pointer;
const OnCompareKeyWithData: TListSortCompare): TAVLTreeNode;
var
RightNode: TAVLTreeNode;
begin
Result:=FindKey(Key,OnCompareKeyWithData);
if Result=nil then exit;
repeat
RightNode:=Result.Successor;
if (RightNode=nil) or (OnCompareKeyWithData(Key,RightNode.Data)<>0) then exit;
Result:=RightNode;
until false;
end;
function TAVLTree.FindLeftMostSameKey(ANode: TAVLTreeNode): TAVLTreeNode;
var
LeftNode: TAVLTreeNode;
Data: Pointer;
begin
if ANode<>nil then begin
Data:=ANode.Data;
Result:=ANode;
repeat
LeftNode:=Result.Precessor;
if (LeftNode=nil) or (Compare(Data,LeftNode.Data)<>0) then break;
Result:=LeftNode;
until false;
end else begin
Result:=nil;
end;
end;
function TAVLTree.FindRightMostSameKey(ANode: TAVLTreeNode): TAVLTreeNode;
var
RightNode: TAVLTreeNode;
Data: Pointer;
begin
if ANode<>nil then begin
Data:=ANode.Data;
Result:=ANode;
repeat
RightNode:=Result.Successor;
if (RightNode=nil) or (Compare(Data,RightNode.Data)<>0) then break;
Result:=RightNode;
until false;
end else begin
Result:=nil;
end;
end;
function TAVLTree.FindNearest(Data: Pointer): TAVLTreeNode;
var Comp: integer;
begin
Result:=Root;
while (Result<>nil) do begin
Comp:=Compare(Data,Result.Data);
if Comp=0 then exit;
if Comp<0 then begin
if Result.Left<>nil then
Result:=Result.Left
else
exit;
end else begin
if Result.Right<>nil then
Result:=Result.Right
else
exit;
end;
end;
end;
function TAVLTree.FindPointer(Data: Pointer): TAVLTreeNode;
// same as Find, but not comparing for key, but same Data too
begin
Result:=FindLeftMost(Data);
while (Result<>nil) do begin
if Result.Data=Data then break;
Result:=Result.Successor;
if Result=nil then exit;
if Compare(Data,Result.Data)<>0 then exit(nil);
end;
end;
function TAVLTree.FindLeftMost(Data: Pointer): TAVLTreeNode;
var
Left: TAVLTreeNode;
begin
Result:=Find(Data);
while (Result<>nil) do begin
Left:=Result.Precessor;
if (Left=nil) or (Compare(Data,Left.Data)<>0) then break;
Result:=Left;
end;
end;
function TAVLTree.FindRightMost(Data: Pointer): TAVLTreeNode;
var
Right: TAVLTreeNode;
begin
Result:=Find(Data);
while (Result<>nil) do begin
Right:=Result.Successor;
if (Right=nil) or (Compare(Data,Right.Data)<>0) then break;
Result:=Right;
end;
end;
function TAVLTree.FindInsertPos(Data: Pointer): TAVLTreeNode;
var Comp: integer;
begin
Result:=Root;
while (Result<>nil) do begin
Comp:=Compare(Data,Result.Data);
if Comp<0 then begin
if Result.Left<>nil then
Result:=Result.Left
else
exit;
end else begin
if Result.Right<>nil then
Result:=Result.Right
else
exit;
end;
end;
end;
procedure TAVLTree.Init;
begin
FNodeClass:=TAVLTreeNode;
end;
procedure TAVLTree.NodeAdded(aNode: TAVLTreeNode);
begin
// for descendants to override
end;
procedure TAVLTree.RotateLeft(aNode: TAVLTreeNode);
{ Parent Parent
| |
Node => OldRight
/ \ /
Left OldRight Node
/ / \
OldRightLeft Left OldRightLeft }
var
AParent, OldRight, OldRightLeft: TAVLTreeNode;
begin
OldRight:=aNode.Right;
OldRightLeft:=OldRight.Left;
AParent:=aNode.Parent;
if AParent<>nil then begin
if AParent.Left=aNode then
AParent.Left:=OldRight
else
AParent.Right:=OldRight;
end else
fRoot:=OldRight;
OldRight.Parent:=AParent;
aNode.Parent:=OldRight;
aNode.Right:=OldRightLeft;
if OldRightLeft<>nil then
OldRightLeft.Parent:=aNode;
OldRight.Left:=aNode;
end;
procedure TAVLTree.RotateRight(aNode: TAVLTreeNode);
{ Parent Parent
| |
Node => OldLeft
/ \ \
OldLeft Right Node
\ / \
OldLeftRight OldLeftRight Right }
var
AParent, OldLeft, OldLeftRight: TAVLTreeNode;
begin
OldLeft:=aNode.Left;
OldLeftRight:=OldLeft.Right;
AParent:=aNode.Parent;
if AParent<>nil then begin
if AParent.Left=aNode then
AParent.Left:=OldLeft
else
AParent.Right:=OldLeft;
end else
fRoot:=OldLeft;
OldLeft.Parent:=AParent;
aNode.Parent:=OldLeft;
aNode.Left:=OldLeftRight;
if OldLeftRight<>nil then
OldLeftRight.Parent:=aNode;
OldLeft.Right:=aNode;
end;
procedure TAVLTree.SwitchPositionWithSuccessor(aNode, aSuccessor: TAVLTreeNode);
{ called by delete, when aNode.Left<>nil and aNode.Right<>nil
Switch ANode position with Successor
Because ANode.Right<>nil the Successor is a child of ANode }
var
OldBalance: Integer;
OldParent, OldLeft, OldRight,
OldSuccParent, OldSuccLeft, OldSuccRight: TAVLTreeNode;
begin
OldBalance:=aNode.Balance;
aNode.Balance:=aSuccessor.Balance;
aSuccessor.Balance:=OldBalance;
OldParent:=aNode.Parent;
OldLeft:=aNode.Left;
OldRight:=aNode.Right;
OldSuccParent:=aSuccessor.Parent;
OldSuccLeft:=aSuccessor.Left;
OldSuccRight:=aSuccessor.Right;
if OldParent<>nil then begin
if OldParent.Left=aNode then
OldParent.Left:=aSuccessor
else
OldParent.Right:=aSuccessor;
end else
fRoot:=aSuccessor;
aSuccessor.Parent:=OldParent;
if OldSuccParent<>aNode then begin
if OldSuccParent.Left=aSuccessor then
OldSuccParent.Left:=aNode
else
OldSuccParent.Right:=aNode;
aSuccessor.Right:=OldRight;
aNode.Parent:=OldSuccParent;
if OldRight<>nil then
OldRight.Parent:=aSuccessor;
end else begin
{ aNode aSuccessor
\ => \
aSuccessor aNode }
aSuccessor.Right:=aNode;
aNode.Parent:=aSuccessor;
end;
aNode.Left:=OldSuccLeft;
if OldSuccLeft<>nil then
OldSuccLeft.Parent:=aNode;
aNode.Right:=OldSuccRight;
if OldSuccRight<>nil then
OldSuccRight.Parent:=aNode;
aSuccessor.Left:=OldLeft;
if OldLeft<>nil then
OldLeft.Parent:=aSuccessor;
end;
function TAVLTree.FindSuccessor(ANode: TAVLTreeNode): TAVLTreeNode;
begin
if ANode<>nil then
Result:=ANode.Successor
else
Result:=nil;
end;
function TAVLTree.FindPrecessor(ANode: TAVLTreeNode): TAVLTreeNode;
begin
if ANode<>nil then
Result:=ANode.Precessor
else
Result:=nil;
end;
procedure TAVLTree.MoveDataLeftMost(var ANode: TAVLTreeNode);
var
LeftMost, PreNode: TAVLTreeNode;
Data: Pointer;
begin
if ANode=nil then exit;
LeftMost:=ANode;
repeat
PreNode:=FindPrecessor(LeftMost);
if (PreNode=nil) or (Compare(ANode,PreNode)<>0) then break;
LeftMost:=PreNode;
until false;
if LeftMost=ANode then exit;
Data:=LeftMost.Data;
LeftMost.Data:=ANode.Data;
ANode.Data:=Data;
ANode:=LeftMost;
end;
procedure TAVLTree.MoveDataRightMost(var ANode: TAVLTreeNode);
var
RightMost, PostNode: TAVLTreeNode;
Data: Pointer;
begin
if ANode=nil then exit;
RightMost:=ANode;
repeat
PostNode:=FindSuccessor(RightMost);
if (PostNode=nil) or (Compare(ANode,PostNode)<>0) then break;
RightMost:=PostNode;
until false;
if RightMost=ANode then exit;
Data:=RightMost.Data;
RightMost.Data:=ANode.Data;
ANode.Data:=Data;
ANode:=RightMost;
end;
procedure TAVLTree.ConsistencyCheck;
procedure E(Msg: string);
begin
raise Exception.Create('TAVLTree.ConsistencyCheck: '+Msg);
end;
var
RealCount: SizeInt;
begin
RealCount:=0;
if FRoot<>nil then begin
FRoot.ConsistencyCheck(Self);
RealCount:=FRoot.GetCount;
end;
if Count<>RealCount then
E('Count<>RealCount');
end;
procedure TAVLTree.FreeAndClear;
procedure FreeNodeData(ANode: TAVLTreeNode);
begin
if ANode=nil then exit;
FreeNodeData(ANode.Left);
FreeNodeData(ANode.Right);
if ANode.Data<>nil then TObject(ANode.Data).Free;
ANode.Data:=nil;
end;
// TAVLTree.FreeAndClear
begin
// free all data
FreeNodeData(Root);
// free all nodes
Clear;
end;
procedure TAVLTree.FreeAndDelete(ANode: TAVLTreeNode);
var OldData: TObject;
begin
OldData:=TObject(ANode.Data);
Delete(ANode);
OldData.Free;
end;
function TAVLTree.Equals(Obj: TObject): boolean;
begin
if Obj is TAVLTree then
Result:=IsEqual(TAVLTree(Obj),false)
else
Result:=inherited Equals(Obj);
end;
function TAVLTree.IsEqual(aTree: TAVLTree; CheckDataPointer: boolean): boolean;
var
MyNode, OtherNode: TAVLTreeNode;
begin
if aTree=Self then exit(true);
Result:=false;
if aTree=nil then exit;
if Count<>aTree.Count then exit;
if OnCompare<>aTree.OnCompare then exit;
if OnObjectCompare<>aTree.OnObjectCompare then exit;
if NodeClass<>aTree.NodeClass then exit;
MyNode:=FindLowest;
OtherNode:=aTree.FindLowest;
while MyNode<>nil do begin
if OtherNode=nil then exit;
if CheckDataPointer then begin
if MyNode.Data<>OtherNode.Data then exit;
end else begin
if Compare(MyNode.Data,OtherNode.Data)<>0 then exit;
end;
MyNode:=MyNode.Successor;
OtherNode:=OtherNode.Successor;
end;
if OtherNode<>nil then exit;
Result:=true;
end;
procedure TAVLTree.Assign(aTree: TAVLTree);
procedure AssignNode(var MyNode: TAVLTreeNode; OtherNode: TAVLTreeNode);
begin
MyNode:=NewNode;
MyNode.Data:=OtherNode.Data;
MyNode.Balance:=OtherNode.Balance;
if OtherNode.Left<>nil then begin
AssignNode(MyNode.Left,OtherNode.Left);
MyNode.Left.Parent:=MyNode;
end;
if OtherNode.Right<>nil then begin
AssignNode(MyNode.Right,OtherNode.Right);
MyNode.Right.Parent:=MyNode;
end;
end;
begin
if aTree=nil then
raise Exception.Create('TAVLTree.Assign aTree=nil');
if IsEqual(aTree,true) then exit;
Clear;
SetCompares(aTree.OnCompare,aTree.OnObjectCompare);
NodeClass:=aTree.NodeClass;
if aTree.Root<>nil then
AssignNode(fRoot,aTree.Root);
FCount:=aTree.Count;
end;
function TAVLTree.Compare(Data1, Data2: Pointer): integer;
begin
if Assigned(FOnCompare) then
Result:=FOnCompare(Data1,Data2)
else
Result:=FOnObjectCompare(Self,Data1,Data2);
end;
procedure TAVLTree.WriteReportToStream(s: TStream);
procedure WriteStr(const Txt: string);
begin
if Txt='' then exit;
s.Write(Txt[1],length(Txt));
end;
procedure WriteTreeNode(ANode: TAVLTreeNode);
var
b: String;
IsLeft: boolean;
AParent: TAVLTreeNode;
WasLeft: Boolean;
begin
if ANode=nil then exit;
WriteTreeNode(ANode.Right);
AParent:=ANode;
WasLeft:=false;
b:='';
while AParent<>nil do begin
if AParent.Parent=nil then begin
if AParent=ANode then
b:='--'+b
else
b:=' '+b;
break;
end;
IsLeft:=AParent.Parent.Left=AParent;
if AParent=ANode then begin
if IsLeft then
b:='\-'
else
b:='/-';
end else begin
if WasLeft=IsLeft then
b:=' '+b
else
b:='| '+b;
end;
WasLeft:=IsLeft;
AParent:=AParent.Parent;
end;
b:=b+NodeToReportStr(ANode)+LineEnding;
WriteStr(b);
WriteTreeNode(ANode.Left);
end;
// TAVLTree.WriteReportToStream
begin
WriteStr('-Start-of-AVL-Tree-------------------'+LineEnding);
WriteTreeNode(fRoot);
WriteStr('-End-Of-AVL-Tree---------------------'+LineEnding);
end;
function TAVLTree.NodeToReportStr(aNode: TAVLTreeNode): string;
begin
Result:=Format('%p Self=%p Parent=%p Balance=%d',
[aNode.Data, Pointer(aNode),Pointer(aNode.Parent), aNode.Balance]);
end;
function TAVLTree.ReportAsString: string;
var ms: TMemoryStream;
begin
Result:='';
ms:=TMemoryStream.Create;
try
WriteReportToStream(ms);
ms.Position:=0;
SetLength(Result,ms.Size);
if Result<>'' then
ms.Read(Result[1],length(Result));
finally
ms.Free;
end;
end;
procedure TAVLTree.SetOnCompare(const AValue: TListSortCompare);
begin
if AValue=nil then
SetCompares(nil,FOnObjectCompare)
else
SetCompares(AValue,nil);
end;
procedure TAVLTree.SetNodeManager(NewMgr: TBaseAVLTreeNodeManager;
AutoFree: boolean);
// only allowed just after create.
begin
if fNodeMgr=NewMgr then exit;
if Count>0 then
raise Exception.Create('TAVLTree.SetNodeManager');
if fNodeMgrAutoFree then
FreeAndNil(fNodeMgr);
fNodeMgr:=NewMgr;
fNodeMgrAutoFree:=AutoFree;
end;
{ TAVLTreeNode }
function TAVLTreeNode.TreeDepth: integer;
// longest WAY down. e.g. only one node => 0 !
var LeftDepth, RightDepth: integer;
begin
if Left<>nil then
LeftDepth:=Left.TreeDepth+1
else
LeftDepth:=0;
if Right<>nil then
RightDepth:=Right.TreeDepth+1
else
RightDepth:=0;
if LeftDepth>RightDepth then
Result:=LeftDepth
else
Result:=RightDepth;
end;
procedure TAVLTreeNode.ConsistencyCheck(Tree: TAVLTree);
procedure E(Msg: string);
begin
raise Exception.Create('TAVLTreeNode.ConsistencyCheck: '+Msg);
end;
var
LeftDepth: SizeInt;
RightDepth: SizeInt;
begin
// test left child
if Left<>nil then begin
if Left.Parent<>Self then
E('Left.Parent<>Self');
if Tree.Compare(Left.Data,Data)>0 then
E('Compare(Left.Data,Data)>0');
Left.ConsistencyCheck(Tree);
end;
// test right child
if Right<>nil then begin
if Right.Parent<>Self then
E('Right.Parent<>Self');
if Tree.Compare(Data,Right.Data)>0 then
E('Compare(Data,Right.Data)>0');
Right.ConsistencyCheck(Tree);
end;
// test balance
if Left<>nil then
LeftDepth:=Left.TreeDepth+1
else
LeftDepth:=0;
if Right<>nil then
RightDepth:=Right.TreeDepth+1
else
RightDepth:=0;
if Balance<>(RightDepth-LeftDepth) then
E('Balance['+IntToStr(Balance)+']<>(RightDepth['+IntToStr(RightDepth)+']-LeftDepth['+IntToStr(LeftDepth)+'])');
end;
function TAVLTreeNode.GetCount: SizeInt;
begin
Result:=1;
if Left<>nil then inc(Result,Left.GetCount);
if Right<>nil then inc(Result,Right.GetCount);
end;
function TAVLTreeNode.Successor: TAVLTreeNode;
begin
Result:=Right;
if Result<>nil then begin
while (Result.Left<>nil) do Result:=Result.Left;
end else begin
Result:=Self;
while (Result.Parent<>nil) and (Result.Parent.Right=Result) do
Result:=Result.Parent;
Result:=Result.Parent;
end;
end;
function TAVLTreeNode.Precessor: TAVLTreeNode;
begin
Result:=Left;
if Result<>nil then begin
while (Result.Right<>nil) do Result:=Result.Right;
end else begin
Result:=Self;
while (Result.Parent<>nil) and (Result.Parent.Left=Result) do
Result:=Result.Parent;
Result:=Result.Parent;
end;
end;
procedure TAVLTreeNode.Clear;
begin
Parent:=nil;
Left:=nil;
Right:=nil;
Balance:=0;
Data:=nil;
end;
{ TAVLTreeNodeMemManager }
constructor TAVLTreeNodeMemManager.Create;
begin
{$IFDEF CheckAVLTreeNodeManager}
FThreadId:=GetCurrentThreadId;
{$ENDIF}
inherited Create;
FFirstFree:=nil;
FFreeCount:=0;
FCount:=0;
FMinFree:=100;
FMaxFreeRatio:=8; // 1:1
end;
destructor TAVLTreeNodeMemManager.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TAVLTreeNodeMemManager.DisposeNode(ANode: TAVLTreeNode);
begin
if ANode=nil then exit;
{$IFDEF CheckAVLTreeNodeManager}
if GetCurrentThreadId<>FThreadId then
raise Exception.Create('TAVLTreeNodeMemManager.DisposeNode not thread safe!');
{$ENDIF}
if FCount < 0 then
raise Exception.CreateFmt(
'%s.DisposeNode: FCount (%d) is negative. Should not happen.'
+' FFreeCount=%d, FMinFree=%d, FMaxFreeRatio=%d.',
[ClassName, FCount, FFreeCount, FMinFree, FMaxFreeRatio]);
if (FFreeCount<FMinFree) or (FFreeCount<((FCount shr 3)*FMaxFreeRatio)) then
begin
// add ANode to Free list
ANode.Clear;
ANode.Right:=FFirstFree;
FFirstFree:=ANode;
inc(FFreeCount);
if (FFreeCount>(((8+FMaxFreeRatio)*FCount) shr 3)) then begin
DisposeFirstFreeNode;
DisposeFirstFreeNode;
end;
end else begin
// free list full -> free the ANode
ANode.Free;
end;
dec(FCount);
end;
function TAVLTreeNodeMemManager.NewNode: TAVLTreeNode;
begin
{$IFDEF CheckAVLTreeNodeManager}
if GetCurrentThreadId<>FThreadId then
raise Exception.Create('TAVLTreeNodeMemManager.NewNode: not thread safe!');
{$ENDIF}
if FFirstFree<>nil then begin
// take from free list
Result:=FFirstFree;
FFirstFree:=FFirstFree.Right;
Result.Right:=nil;
dec(FFreeCount);
end else begin
// free list empty -> create new node
Result:=TAVLTreeNode.Create;
end;
inc(FCount);
end;
procedure TAVLTreeNodeMemManager.Clear;
var ANode: TAVLTreeNode;
begin
{$IFDEF CheckAVLTreeNodeManager}
if GetCurrentThreadId<>FThreadId then
raise Exception.Create('TAVLTreeNodeMemManager.Clear: not thread safe!');
{$ENDIF}
while FFirstFree<>nil do begin
ANode:=FFirstFree;
FFirstFree:=FFirstFree.Right;
ANode.Right:=nil;
ANode.Free;
end;
FFreeCount:=0;
end;
procedure TAVLTreeNodeMemManager.SetMaxFreeRatio(NewValue: SizeInt);
begin
if NewValue<0 then NewValue:=0;
if NewValue=FMaxFreeRatio then exit;
FMaxFreeRatio:=NewValue;
end;
procedure TAVLTreeNodeMemManager.SetMinFree(NewValue: SizeInt);
begin
if NewValue<0 then NewValue:=0;
if NewValue=FMinFree then exit;
FMinFree:=NewValue;
end;
procedure TAVLTreeNodeMemManager.DisposeFirstFreeNode;
var OldNode: TAVLTreeNode;
begin
if FFirstFree=nil then exit;
OldNode:=FFirstFree;
FFirstFree:=FFirstFree.Right;
dec(FFreeCount);
OldNode.Right:=nil;
OldNode.Free;
end;
initialization
LazNodeMemManager:=TAVLTreeNodeMemManager.Create;
finalization
LazNodeMemManager.Free;
LazNodeMemManager:=nil;
end.
|