开始学习二叉查找树
目标:在两个半月内基本掌握相关基本查询,以及Splay、SBT、Trie这三种特殊树的形式。
千里之行,始于足下。
一段非常普通的bst
1 program bst; 2 3 Type 4 node=^rec; 5 rec=record 6 lch,rch:node; 7 d,pos:longint; 8 end; 9 10 Var 11 h,u:node; 12 i,o,n:longint; 13 Procedure init(var p:node;k,po:longint); 14 begin 15 p^.lch:=nil; 16 p^.rch:=nil; 17 p^.d:=k; 18 p^.pos:=po; 19 end; 20 21 Procedure ins(var p:node;q,po:longint); 22 var 23 p1:node; 24 begin 25 if p=nil then 26 begin 27 new(p); 28 init(p,q,po); 29 exit; 30 end; 31 if q<=p^.d then ins(p^.lch,q,po) else ins(p^.rch,q,po); 32 end; 33 34 Function find(p:node;q:longint):node; 35 begin 36 if p=nil then exit(nil); 37 if p^.d=q then exit(p); 38 if q<=p^.d then exit(find(p^.lch,q)) else 39 exit(find(p^.rch,q)); 40 end; 41 42 Procedure delete(var p:node); 43 var 44 t,s,q:node; 45 begin 46 if p^.lch=nil then 47 begin 48 q:=p; 49 p:=p^.rch; 50 dispose(q); 51 end else 52 if p^.rch=nil then 53 begin 54 q:=p; 55 p:=p^.lch; 56 dispose(q); 57 end else 58 begin 59 t:=p; 60 s:=p^.lch; 61 while s^.rch<>nil do 62 begin 63 t:=s; 64 s:=s^.rch; 65 end; 66 p^.d:=s^.d; 67 p^.pos:=s^.pos; 68 if t<>p then 69 t^.rch:=s^.lch 70 else 71 t^.lch:=s^.lch; 72 dispose(s); 73 end; 74 end; 75 76 Procedure delBST(var p:node;q:longint); 77 begin 78 if p=nil then exit; 79 if p^.d=q then delete(p) else 80 if q<p^.d then delbst(p^.lch,q) else 81 delbst(p^.rch,q); 82 end; 83 84 begin 85 readln(n); 86 for i:=1 to n do 87 begin 88 readln(o); 89 ins(h,o,i); 90 end; 91 delbst(h,5); 92 while true do 93 begin 94 readln(o); 95 if find(h,o)=nil then writeln('Not found!') else writeln(find(h,o)^.pos); 96 end; 97 end.