: n , . , . , . . :
1. ;
2. nL = n div 2 ;
3. nR = n-nL-1 .
Tree.
program BinTree; { ,
, }
type ref = ^Node;
Node= record
Inf: integer;
Left,Right: ref
end;
var Root: ref; { }
H: integer; { }
n: integer; { }
function Tree(n: integer):ref; { n }
var t: ref; x,nL,nR: integer;
begin
If (n=0) then Tree:=nil
else begin
nL:=n div 2; { }
nR:=n-nL-1; { }
read(x);
new(t); { }
t^.Inf:= x; {, }
t^.Left:=Tree(nL); { }
t^.Right:=Tree(nR); { }
Tree:= t
end
end; { Tree }
procedure PrintTree (t: ref; h: integer); { . .
t ; h , }
const blank=' '; { }
var i: integer;
begin
if (t<>nil) then begin
PrintTree (t^.Right, h+1);
for i:=1 to h do write(blank); { h}
writeln(t^.Inf);
PrintTree (t^.Left, h+1) end
end;
function Height(t:ref):integer; { . }
var hL, hR: integer;
begin
if (t=nil) then Height:= -1 { , 1}
else begin
hL:=Height(t^.Left); { }
hR:=Height(t^.Right); { }
if (hL>hR) then Height:=hL + 1
else Height:=hR + 1
end
end; { Height}
begin { }
write('n='); readln(n);
Root:= Tree(n);
PrintTree(Root, 0); { 0, }
H:=Height(Root); writeln(' H=', H)
End.
n=7 1, 2, 3, 4, 5, 6, 7, :
7 5 6 1 4 2 3 | : h=2 h=1 h=2 h=0 h=2 h=1 h=2 | |
H=2 |
. , . , .
|
|
,
a*b + c/d . : , .
.
Root , L R .
.
1) , (Root, L, R , )
, :
+*ab/cd
2) , (L, R, Root , )
, :
ab*cd/+
, .
3) , (L, Root, R , )
, , : a*b + c/d
4) (R, Root, L , ) .
t, , , . t , . OP , , , ..
:
(, , );
( ).
procedure Prefix (t: ref); { Root, L, R} begin { } if (t<>nil) then begin OP(t); { } Prefix(t^.Left); { } Prefix(t^.Right) { } end end; | procedure Postfix(t: ref); { L, R Root} begin { } if (t<>nil) then begin Postfix(t^.Left);{ } Postfix(t^.Right);{ } OP(t) { } end end; | |
procedure Infix(t: ref); { L, Root< R} begin { , } if (t<>nil) then begin Infix(t^.Left);{ } OP(t); { } Infix(t^.Right) { } end end; | ||
, , .
, , .
|
|
. , , ( ), . , : O(C×log2n), O(n). |
, , , .
, :
- , .
- , =1.
, . : .
program TreeSearch; { }
type ref=^node;
node=record
key:integer;
count:integer;
left,right:ref
end;
var Root:ref; k:integer;
procedure Gen(x:integer; var t:ref); { }
begin
new(t);
t^.key:=x; t^.count:=1;
t^.left:=nil; t^.right:=nil
end;
procedure Search (x:integer; var t:ref); { t}
begin
if t=nil
then Gen(x,t) { , .. x }
else if (x = t^.key)
then t^.count:=t^.count+1 { x }
else if (x < t^.key)
then Search(x, t^.left) { }
else Search(x, t^.right) { }
end;
procedure PrintTree(t:ref; h:integer); { . }
var i:integer;
begin
if t<>nil then
begin
PrintTree(t^.right,h+1);
for i:=1 to h do write(' ');
writeln(t^.key, _', t^.count);
PrintTree(t^.left, h+1);
end
end;
procedure Infix(t: ref); { . }
begin
if (t<>nil)
then begin
Infix(t^.Left); { }
write(t^.key:3);
Infix(t^.Right) { }
end
end;
Begin
Root:=nil; { }
write('='); readln(k);
while (k<>0) do { k=0 }
begin
Search(k, Root);
write('='); readln(k);
end;
PrintTree(Root,0);{ }
Infix(Root); { }
End.