tree_depth(leaf(_), 0).
tree_depth(node(L,R), D):-
  tree_depth(L, DL),
  tree_depth(R, DR),
  D is max(DL, DR) + 1.

depth_tree(Tree):-
  depth_tree(Tree, 0).

depth_tree(leaf(D), D).
depth_tree(node(L,R), D):-
  D1 is D+1,
  depth_tree(L, D1),
  depth_tree(R, D1).

simplify(N, 0*x+N):-
  number(N).
simplify(x, 1*x+0).
simplify(U+V, A*x+B):-
  simplify(U, AU*x+BU),
  simplify(V, AV*x+BV),
  A is AU + AV,
  B is BU + BV.
simplify(U-V, S):-
  simplify(U+ -1*V, S).
simplify(U*V, A*x+B):-
  ( simplify(U, 0*x+BU) -> simplify(V, AV*x+BV),
    A is BU*AV,
    B is BU*BV
  ; simplify(V, 0*x+BV) -> simplify(U, AU*x+BU),
    A is BV*AU,
    B is BV*BU
  ).
