So I have a task to create a binary tree using the following facts that define each node with its two child nodes:
node(root, a, b).
node(a, c, d).
node(b, z, y).
node(c, e, f).
node(d, x, w).
node(e, g, h).
node(z, v, u).
node(u, t, s).
node(t, r, q).
I want to define the rule height(RootNode, Height) to calculate the height of the binary tree that starts at the RootNode. The height of a tree is the longest distance (number of nodes) from the root node to the farthest away leaf node. A leaf node is a node that doesn’t have any children. The height of a leaf node is 1.
The code I currently have is:
node(root, a, b).
node(a, c, d).
node(b, z, y).
node(c, e, f).
node(d, x, w).
node(e, g, h).
node(z, v, u).
node(u, t, s).
node(t, r, q).
height(nil, 0).
height(RootNode, Height):-
node(RootNode, Left, Right),
height(Left, LH),
height(Right, RH),
Height is max(LH, RH) + 1.
At the moment, I'm really stuck and would love to know what happens to this code when it runs, why I've done this incorrectly and where I should look to improve further? Appreciate any help.
nil? what isf? should it benode(c, e, nil).ornode(f, nil, nil).?