Write Prolog rules as described in the questions below. You may use any Prolog b
ID: 3902736 • Letter: W
Question
Write Prolog rules as described in the questions below. You may use any Prolog builtin predicates.
A binary tree is defined by the structure node(left,right), where left and right can be either another node or any Prolog data item.
Write the rule isBalanced(Tree) that determines if the tree is balanced. A binary tree is balanced if, at every node, the difference between the number of leaves appearing in the left and right subtree is at most one. (A tree which contains just one leaf is considered balanced.)
For example: ?- isBalanced(1).
true.
?- isBalanced(node(1,2)).
true.
?- isBalanced(node(1,node(1,node(1,2)))).
false.
Explanation / Answer
A binary tree is made up of a root node and two successors following the same pattern.
For eg we represent the empty tree as null and non empty tree as T(V,left,right)
T= roo node or parent node
left= left subtree or subnode
right= right subtree or subnode.
Example of tree :
Tree= T(a,T(b,T(d,null,null),T(e,null,null),T(c,null,T(f,T(g,null,null),null)))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.