title: Prolog: Building a completely balanced tree
body: <p>Does anyone know of any simpler ways of building completely balanced trees in Prolog?</p>
  
  <p>Here's one solution I've found but I'm wondering if anyone knows of any simpler solutions?</p>
  
  <p>This one is pretty simple but took me a little while to grasp exactly how it works.</p>
  
  <p>Thanks :).</p>
  
  <pre><code>% from given solution
  
  cbal_tree( 0, nil ) :- !.
  cbal_tree( N, t(x,L,R) ) :- 
      N &gt; 0,
  
      N0 is N - 1, % if N is 4, this would be 3
  
      N1 is N0 mod 2, % if N is 4, this would be 3 mod 2 = 1
      N2 is N0 - N1, % if N is 4, this would be 3-1= 2
  
      distrib( N1, N2, LeftNode, RightNode ),
  
      cbal_tree( LeftNode, L ), 
      cbal_tree( RightNode, R ).
  
  distrib(N,N,N,N) :- !.
  distrib(N1,N2,N1,N2). % giving these two clauses (*) 1,2,?,? could give 1,2 or 2,1
  distrib(N1,N2,N2,N1). % (*)
  </code></pre>