二叉樹是樹結構中的一種,任意樹都能很容易的轉換成相應的二叉有序樹,二叉樹的存儲和算法相對簡單,存儲效率高。二叉樹是n(n>=0)個結點的有限集合,它或者爲空集(n=0),或者是由一個根結點和兩個互不相交的分別稱爲根的左子樹和右子樹組成。二叉樹是由根結點、左子樹、右子樹三個基本單元,相應的遍歷算法也有三種,一下是根據C語言改編的Delphi的二叉樹實現及遍歷算法。
打開Delphi,選擇File-new-other-Console Application,新建一個控制檯應用程序。源代碼如下:
program Btree;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
Ptree=^Ttree;
Ttree=record
data:Char;
lchild,rchild:Ptree;
end;
function CreateTree():Ptree; //按前序遍歷次序創建二叉樹
var
ch:Char;
root:Ptree;
begin
Writeln('Please input the data,''$'' is the end.');
Readln(ch);
if ch='$' then
begin
Result:=nil;
Exit;
end
else
begin
New(root);
root^.data:=ch;
root^.lchild:=CreateTree();
root^.rchild:=CreateTree();
Result:=root;
end;
Writeln('OK!');
end;
procedure preorder(root:Ptree); //前序遍歷二叉樹根左右
begin
if Assigned(root) then
begin
Write(root^.data);
preorder(root^.lchild);
preorder(root^.rchild);
end;
end;
procedure inorder(root:Ptree); //中序遍歷二叉樹左根右
begin
if Assigned(root) then
begin
inorder(root^.lchild);
Write(root^.data);
inorder(root^.rchild);
end;
end;
procedure postorder(root:Ptree);//後序遍歷二叉樹左右根
begin
if Assigned(root) then
begin
postorder(root^.lchild);
postorder(root^.rchild);
Write(root^.data);
end;
end;
function treedepth(root:Ptree):Integer; //二叉樹的深度
var
depth,dl,dr:integer;
begin
if not Assigned(root) then
depth:=0
else
begin
dl:=treedepth(root^.lchild); //獲取左子樹深度
dr:=treedepth(root^.rchild); //獲取右子樹深度
if dl>dr then
depth:=dl+1
else
depth:=dr+1;
end;
Result:=depth;
end;
function numofleaf(root:Ptree):Integer; //二叉樹葉子數
var
num,num1,num2:Integer;
begin
if Assigned(root) then
begin
if (not Assigned(root^.lchild)) and (not Assigned(root^.rchild)) then
num:=1
else
begin
num1:=numofleaf(root^.lchild); //獲取左子樹葉子數
num2:=numofleaf(root^.rchild); //獲取右子樹葉子數
num:=num1+num2;
end;
end
else
num:=0;
Result:=num;
end;
var
root:Ptree;
i:Integer;
begin
Writeln('Create a btree');
Writeln('Please input nodes of tree');
root:=CreateTree();
if root=nil then
Writeln('This is an empty tree!')
else
begin
Writeln('1.The preorder traverse ');
Writeln('2.The inorder traverse ');
Writeln('3.The postorder traverse ');
Writeln('Please choose a kind of order');
Readln(i);
case i of
1:preorder(root);
2:inorder(root);
3:postorder(root)
else
Writeln('error!');
end;
end;
Writeln;
Writeln('The depth of the btree is ',treedepth(root));
Writeln('The leafnumber of the btree is ',numofleaf(root));
Readln;
end.
運行後效果如下所示: