with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Deallocation;

package body Trees is
   procedure Free is new Ada.Unchecked_Deallocation (Tree_Node, Tree);

   procedure Insert (T : in out Tree; K : Integer) is
   begin
      if T = null then
         T := new Tree_Node'(Key => K, Left => null, Right => null);
      elsif K < T.Key then
         Insert (T.Left, K);
      elsif K > T.Key then
         Insert (T.Right, K);
      end if;
   end Insert;

   procedure Contains (T : Tree; K : Integer; Found : out Boolean) is
   begin
      if T = null then
         Found := False;
      elsif K < T.Key then
         Contains (T.Left, K, Found);
      elsif K > T.Key then
         Contains (T.Right, K, Found);
      else
         Found := True;
      end if;
   end Contains;

   procedure Print_In_Order (T : Tree) is
   begin
      if T /= null then
         Print_In_Order (T.Left);
         Put (Integer'Image (T.Key));
         Print_In_Order (T.Right);
      end if;
   end Print_In_Order;

   procedure Clear (T : in out Tree) is
      L : Tree;
      R : Tree;
   begin
      if T /= null then
         L := T.Left;
         R := T.Right;
         Free (T);
         Clear (L);
         Clear (R);
      end if;
   end Clear;
end Trees;
