This Prolog library provides predicates for handling binary trees. Binary trees are represented as nil (the empty tree) or as t(L, X, R), where L and R are left and right subtrees. The values in binary trees can be numbers or letters. For binary search trees, the values must be integers.
- Download the file
binary_trees_library.pl. - Load the file into Prolog either in your code or in your interpreter with the following command
use_module('path/to/binary_tree_library.pl'). - Use the predicates.
Below are all the predicates I implemented for the library.
You will find a more detailed usage with code snippets in the binary_tree_library.pl file.
- Returns the height
Hof the binary treeT.
- Succeeds if predicate
Pis true for every value in the treeT.
- Performs a right fold of a predicate over all values in a tree.
- Flattens a tree
T, producing a list of valuesL.
- Counts all nodes in a tree.
- Counts the number of leaves in the binary tree
T.
- Searches for a specified element
Xin a binary treeT.
- Performs a preorder traversal of a binary tree
T.
- Performs an in-order traversal of a binary tree
T.
- Performs a postorder traversal of a binary tree
T.
- Gives a list
Resultcontaining all nodes of depthDin a binary treeT.
- Gives the depth
Dof a node of valueVin a binary treeT.
- Returns true if the node of value
Vis a leaf of the binary treeT.
- Returns true if the binary tree
Tis full.
- Returns true if the binary tree
Tis perfect.
- Returns true if the binary tree
Tis quasi-perfect.
- Returns true if the binary tree
Tis a binary search tree.
- Searches for a specified element
Xin a binary search treeT.
- Inserts a value
Xinto a binary search treeT, producing a treeT1.
- Deletes a specified element
Xfrom a binary search treeT, producing a treeT1.
- Finds the maximum value
Maxin the binary search treeT.
- Finds the minimum value
Minin the binary search treeT.
Here are some examples of trees that I have used to test the code:
my_bst1(T)- Binary search tree with integer values.my_btree(T)- Binary tree with non-integer values.my_full_tree(T)- Full binary tree.my_perfect_tree(T)- Perfect binary tree (also a binary search tree).my_quasi_perfect_tree(T)- Quasi-perfect binary tree (also a binary search tree).my_alphabet_tree(T)- Binary tree with alphabet letters.
Example usage:
?- my_full_tree(_T), is_full(_T).This library is released under the MIT License (see more information about it in file LICENSE).