(*  To compare two trees for equality (or less/greater) is the
  classic "samefringe" problem.  I use a solution involving
  the "gopher function",  attributed by Gabriel 1991 to McCarthy 1977,
 but an equivalent solution was published first by Gruessay in 1976.

  Gabriel writes, "this solution is difficult to understand," but in fact
  the Coq proofs about it are quite straightforward, actually simpler
  than the ones involving list-flattening solutions to samefringe.

   Richard Gabriel, The design of parallel programming languages,
   in Artificial intelligence and mathematical theory of computation,
   ed. Vladimir Lifschitz,  pp. 91-108, Academic Press 1991.

  Patrick Gruessay, "An iterative Lisp solution to the Samefringe problem",
  ACM SIGART Bulletin, Issue 59, p. 14, August 1976.

  John McCarthy. Another Samefringe. ACM SIGART Bulletin, No. 61, February 1977.

*)

Fixpoint gopher (s: tree) : tree :=
 match s with
 | EE => EE
 | T _ sl k sr => match gopher sl with
                          | T _ sll j slr => T Red sll j (T Red slr k sr)
                          | EE => s
                          end
  end.

Lemma shape_gopher: forall a, match gopher a with | T _ (T _ _ _ _) _ _ => False | _ => True end.