请实现平衡二叉树的动态插入和调整过程的演示。
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
ListBox1: TListBox;
ListBox2: TListBox;
Button2: TButton;
Label1: TLabel;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
type
pointer=^node;
node=record
data:real;
left,rightointer;
end;
var
x:real;
rootointer;
{$R *.DFM}
procedure add_tree(x:real;
var pointer);
begin
if p=nil
then
begin
// 加入一节点
new(p);
with p^do
begin
data:=x;
left:=nil;
right:=nil;
end
end
else
with p^do
if x<data
then
add_tree(x,left) //加入左子树
else
add_tree(x,right)//加入右子树
end;
procedure inorder(pointer);
begin
if p<>nil then
begin
inorder(p^.left);
form1.listbox2.items.add(floattostr(p^.data));
inorder(p^.right);
end
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i:integer;
begin
listbox1.clear;
i:=0;
root:=nil;
x:=strtofloat(memo1.lines[0]);
listbox1.items.add(floattostr(x));
while x>0do
begin
i:=i+1;
add_tree(x,root);
x:=strtofloat(memo1.lines);
if (x>0) then
listbox1.items.add(floattostr(x));
end;
end;