Advertisement
Felix0301

EProg Binary Tree Solution

Nov 19th, 2014
2,744
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Eiffel 1.25 KB | None | 0 0
  1. indexing
  2.     description : "Node of a binary search tree."
  3.     date: "$Date$"
  4.     revision: "$Revision$"
  5.  
  6. class
  7.     NODE
  8.  
  9. create
  10.     make
  11.  
  12. feature
  13.  
  14.     value: INTEGER
  15.     left, right: NODE
  16.  
  17.     make (v: INTEGER)
  18.             -- Create node with value `v'.
  19.         do
  20.             value := v
  21.         ensure
  22.             value_set: value = v
  23.         end
  24.  
  25.     traverse
  26.             -- Traverse tree starting from Current.
  27.         do
  28.             if left /= Void then
  29.                 left.traverse
  30.             end
  31.  
  32.             Io.put_string (value.out + "  ")  -- print in order of values
  33.  
  34.             if right /= Void then
  35.                 right.traverse
  36.             end
  37.         end
  38.  
  39.     set_children (l, r: NODE)
  40.             -- Set left and right childred.
  41.         do
  42.             left := l
  43.             right := r
  44.         end
  45.  
  46.     put (n: INTEGER)
  47.             -- Insert a node with value `n' at the right place.
  48.         do
  49.             if n < value then
  50.                 if left = Void then
  51.                     create left.make (n)
  52.                 else
  53.                     left.put (n)
  54.                 end
  55.             else
  56.                 if right = Void then
  57.                     create right.make (n)
  58.                 else
  59.                     right.put (n)
  60.                 end
  61.             end
  62.         end
  63.  
  64.     has (n: INTEGER): BOOLEAN
  65.             -- Returns true if and only if `n' is in the tree rooted by Current.
  66.         do
  67.             if n = value then
  68.                 Result := True
  69.             elseif n < value and left /= Void then
  70.                 Result := left.has (n)
  71.             elseif n >= value and right /= Void then
  72.                 Result := right.has (n)
  73.             end
  74.         end
  75.  
  76. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement