Advertisement
huyhung94

Giải thuật Xóa một phần tử trên BST

Oct 7th, 2013
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 1.10 KB | None | 0 0
  1. program Xoa;
  2. procedure BST_Delete(T,X);
  3.     begin
  4.         P:=T;
  5.         Q:=nil; {Q là cha của P}
  6.         while P# nil do {Tìm x trên cây}
  7.             begin
  8.                 if x=p.data then
  9.                     break
  10.                 Q:=P;
  11.                 if x<P.data then
  12.                     P:=P.P_L
  13.                 else
  14.                     P:=P.P_R;
  15.             end;
  16.         if P=nil then
  17.             write('Không tìm thấy nút cần xóa')
  18.         else    {Tìm thấy và xóa}
  19.             begin
  20.                 if ((P.P_R # nil) and (P.P_R # nil)) then
  21.                     begin   {Nút cần xóa có 2 con, đi tìm nút thay thế}
  22.                         node:=P; Q:=P;
  23.                         P:=P.P_L;
  24.                         while (P.P_R # nil) do
  25.                             begin
  26.                                 Q:=P; P:=P.P_R;
  27.                             end;
  28.                         {Chuyển giá trị nút thay thế vào nút cần xóa}
  29.                         node.data:=P.data;
  30.                     end;
  31.                 {Xóa nút P đang trỏ vào, cho con trỏ child trỏ vào nút con của P}
  32.                 if P.P_R# nil then
  33.                     child:=P.P_R
  34.                 else
  35.                     child:=P.P_L;
  36.                 if T=P then
  37.                     T:=child
  38.                 else
  39.                     if Q.P_L=P then
  40.                         Q.P_L:=child
  41.                     else
  42.                         Q.P_R:=child;
  43.                 Dispose(P);
  44.             end;
  45.     End;
  46. BEGIN
  47.     Nhập cây;
  48.     Nhập giá trị cần xóa X;
  49.     BST_Delete(T,x);
  50.     readln
  51. END.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement