Hi Silvia,
to improve on the semantics of your code you could name your class TBinaryTreeNode - it is a node after all and only aggregating some nodes will produce a binary tree.
Since you stress the decoupling of the new node from its tree-instance, this seems not to be a coding exercise in balanced binary trees. So I present some code for you to study, that in fact is focusing on the forementioned thought of a deep copy:
Delphi-Quellcode:
unit BinTree;
interface
type
PBinaryTreeNode = ^TBinaryTreeNode;
TBinaryTreeNode =
class
private
FValue: Integer;
FLeft: TBinaryTreeNode;
FRight: TBinaryTreeNode;
public
constructor Create(Value: Integer);
function Clone(deep: Boolean = false): TBinaryTreeNode;
property Value: Integer
read FValue;
property Left: TBinaryTreeNode
read FLeft
write FLeft;
property Right: TBinaryTreeNode
read FRight
write FRight;
end;
implementation
constructor TBinaryTreeNode.Create(Value: Integer);
begin
inherited Create;
FValue := Value;
end;
function TBinaryTreeNode.Clone(deep: Boolean = false): TBinaryTreeNode;
begin
Result := TBinaryTreeNode.Create(FValue);
if deep
then
begin
if Assigned(FLeft)
then
Result.Left := FLeft.Clone(true);
if Assigned(FRight)
then
Result.Right := FRight.Clone(true);
end;
end;
end.
To insert a copy of node 77 you could use the following lines of code:
Delphi-Quellcode:
var
bt77, bt1, bt77Clone: TBinaryTreeNode;
procedure TDemoForm.ButtonClick(Sender: TObject);
begin
bt77 := TBinaryTreeNode.Create(77);
bt77Clone := bt77.Clone();
bt77Clone.Right := bt1.Right;
bt1.Right := bt77Clone;
end;
Kind regards
marabu