Binary Trees

A binary tree is either empty or it is composed of a root element and two successors, which are binary trees themselves.

We represent the empty tree by the empty list [] and the non-empty tree by [X,L,R], where X denotes the root node and L and R denote the left and right subtree, respectively.

%%{init: {'theme':'neutral'}}%%
    graph TD
        a((a)) --> b((b))
        a --> c((c))
        b --> d((d))
        b --> e((e))
        c --> n((.))
        c --> f((f))
        f --> g((g))
        f --> n2((.))

The example tree depicted above is therefore represented by the following list:

[a,
    [b,
        [d,[],[]],
        [e,[],[]]
    ],
    [c,
        [],
        [f,
            [g,[],[]],
            []
        ]
    ]
]

Other examples are a binary tree that consists of a root node only: [a, [], []], or an empty binary tree: []. You can check your functions using these example trees.

Problem 54

easy

Check whether a given list represents a binary tree.

Write a function istree which returns true if and only if its argument is a list representing a binary tree. Example:

istree([a, [b,[],[]], []]) == true
istree([a, [b,[],[]]]) == false

Problem 55

intermediate

Construct completely balanced binary tree.

In a completely balanced binary tree, the following property holds for every node: The number of nodes in its left subtree and the number of nodes in its right subtree are almost equal, which means their difference is not greater than one.

Write a function cbal_tree/1 to construct completely balanced binary trees for a given number of nodes. The function should generate all solutions via backtracking. Put the letter x as information into all nodes of the tree.

Example

cbal_tree(4) == 
    t(  x,
        t(  x,  nil,    nil),
        t(  x,
            nil,
            t(  x,  nil,    nil)
        )
    )

Problem 56

intermediate

Symmetric binary tree.

Let us call a binary tree symmetric if you can draw a vertical line through the root node and then the right subtree is the mirror image of the left subtree.

Write a function symmetric/1 to check whether a given binary tree is symmetric.

Hint: Write a function mirror/2 first to check whether one tree is the mirror image of another. We are only interested in the structure, not in the contents of the nodes.

Problem 57

intermediate

Binary search trees (dictionaries).

Use the function add/3, to write a function to construct a binary search tree from a list of integer numbers.

Example

construct([3,2,5,7,1]) ==
    t(  3,
        t(  2,
            t(  1,  nil,    nil),
            nil
        ),
        t(  5,
            nil,
            t(  7,  nil,    nil)
        )
    )

Then use this function to test the solution of the problem P56.

Example

test_symmetric([5,3,18,1,4,12,21]) == true
test_symmetric([3,2,5,7,4]) == false

Problem 58

intermediate

Generate-and-test paradigm.

Apply the generate-and-test paradigm to construct all symmetric, completely balanced binary trees with a given number of nodes. Example: ?- sym_cbal_trees(5,Ts). Ts = [t(x, t(x, nil, t(x, nil, nil)), t(x, t(x, nil, nil), nil)), t(x, t(x, t(x, nil, nil), nil), t(x, nil, t(x, nil, nil))). How many such trees are there with 57 nodes? Investigate about how many solutions there are for a given number of nodes? What if the number is even? Write an appropriate function.

Problem 59

intermediate

Construct height-balanced binary tree.

In a height-balanced binary tree, the following property holds for every node: The height of its left subtree and the height of its right subtree are almost equal, which means their difference is not greater than one. Write a function hbal_tree/2 to construct height-balanced binary trees for a given height. The function should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. Example: ?- hbal_tree(3) == t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), t(x, nil, nil))) . T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), nil)) . etc......No

Problem 60

intermediate

Construct height-balanced binary trees with a given number of node.

Consider a height-balanced binary tree of height H. What is the maximum number of nodes it can contain. Clearly, MaxN = 2**H - 1. However, what is the minimum number MinN? This question is more difficult. Try to find a recursive statement and turn it into a function minNodes/2 defined as follwos:

% minNodes(H,N) :- N is the minimum number of nodes in a height-balanced binary tree of height H. (integer,integer), (+,?. On the other hand, we might ask: what is the maximum height H a height-balanced binary tree with N nodes can have?

% maxHeight(N,H) :- H is the maximum height of a height-balanced binary tree with N nodes (integer,integer), (+,?. Now, we can attack the main problem: construct all the height-balanced binary trees with a given nuber of nodes.

% hbal_tree_nodes(N,T) :- T is a height-balanced binary tree with N nodes. Find out how many height-balanced trees exist for N = 15.

Problem 61

easy

Count the leaves of a binary tre. A leaf is a node with no successors. Write a function count_leaves/2 to count them.

% count_leaves(T,N) :- the binary tree T has N leaves

Problem 61 A

easy

Collect the leaves of a binary tree in a list.

A leaf is a node with no successors. Write a function leaves/2 to collect them in a list.

% leaves(T,S) :- S is the list of all leaves of the binary tree T

Problem 62

easy

Collect the internal nodes of a binary tree in a list.

An internal node of a binary tree has either one or two non-empty successors. Write a function internals/2 to collect them in a list.

% internals(T,S) :- S is the list of internal nodes of the binary tree T.

Problem 62

B (easy) Collect the nodes at a given level in a lis. A node of a binary tree is at level N if the path from the root to the node has length N-1. The root node is at level 1. Write a function atlevel/3 to collect all nodes at a given level in a list.

% atlevel(T,L,S) :- S is the list of nodes of the binary tree T at level . Using atlevel/3 it is easy to construct a function levelorder/2 which creates the level-order sequence of the nodes. However, there are more efficient ways to do that.

Problem 63

intermediate

Construct a complete binary tree.

A complete binary tree with height H is defined as follows: The levels 1,2,3,...,H-1 contain the maximum number of nodes (i.e 2**(i-1) at the level i, note that we start counting the levels from 1 at the root). In level H, which may contain less than the maximum possible number of nodes, all the nodes are "left-adjusted". This means that in a levelorder tree traversal all internal nodes come first, the leaves come second, and empty successors (the nil's which are not really nodes!) come last. Particularly, complete binary trees are used as data structures (or addressing schemes) for heaps. We can assign an address number to each node in a complete binary tree by enumerating the nodes in levelorder, starting at the root with number 1. In doing so, we realize that for every node X with address A the following property holds: The address of X's left and right successors are 2A and 2A+1, respectively, supposed the successors do exist. This fact can be used to elegantly construct a complete binary tree structure. Write a function complete_binary_tree/2 with the following specification:

% complete_binary_tree(N,T) :- T is a complete binary tree with N nodes. (+,?. Test your function in an appropriate way.

Problem 64

intermediate

Layout a binary tree (1).

Given a binary tree as the usual Prolog term t(X,L,R) (or nil). As a preparation for drawing the tree, a layout algorithm is required to determine the position of each node in a rectangular grid. Several layout methods are conceivable, one of them is shown in the illustration below. In this layout strategy, the position of a node v is obtained by the following two rules. x(v) is equal to the position of the node v in the inorder sequenc. y(v) is equal to the depth of the node v in the tre. In order to store the position of the nodes, we extend the Prolog term representing a node (and its successors) as follows:

% nil represents the empty tree (as usual) % t(W,X,Y,L,R) represents a (non-empty) binary tree with root W "positioned" at (X,Y), and subtrees L and . Write a function layout_binary_tree/2 with the following specification:

% layout_binary_tree(T,PT) :- PT is the "positioned" binary tree obtained from the binary tree T. (+,?. Test your function in an appropriate way.

Problem 65

intermediate

Layout a binary tree (2).

An alternative layout method is depicted in the illustration opposite. Find out the rules and write the corresponding Prolog function. Hint: On a given level, the horizontal distance between neighboring nodes is constant. Use the same conventions as in problem P64 and test your function in an appropriate way.

Problem 66

hard

Layout a binary tree (3).

Yet another layout strategy is shown in the illustration opposite. The method yields a very compact layout while maintaining a certain symmetry in every node. Find out the rules and write the corresponding Prolog function. Hint: Consider the horizontal distance between a node and its successor nodes. How tight can you pack together two subtrees to construct the combined binary tree. Use the same conventions as in problem P64 and P65 and test your function in an appropriate way. Note: This is a difficult problem. Don't give up too early. Which layout do you like most?

Problem 67

intermediate

A string representation of binary tree.

Somebody represents binary trees as strings of the following type (see example opposite). a(b(d,e),c(,f(g,)). a) Write a Prolog function which generates this string representation, if the tree is given as usual (as nil or t(X,L,R) term). Then write a function which does this inverse; i.e. given the string representation, construct the tree in the usual form. Finally, combine the two functions in a single function tree_string/2 which can be used in both directions. b) Write the same function tree_string/2 using difference lists and a single function tree_dlist/2 which does the conversion between a tree and a difference list in both directions. For simplicity, suppose the information in the nodes is a single letter and there are no spaces in the string.

Problem 68

intermediate

Preorder and inorder sequences of binary tree.

We consider binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. a) Write functions preorder/2 and inorder/2 that construct the preorder and inorder sequence of a given binary tree, respectively. The results should be atoms, e.g. 'abdecfg' for the preorder sequence of the example in problem P67. b) Can you use preorder/2 from problem part a) in the reverse direction; i.e. given a preorder sequence, construct a corresponding tree? If not, make the necessary arrangements. c) If both the preorder sequence and the inorder sequence of the nodes of a binary tree are given, then the tree is determined unambiguously. Write a function pre_in_tree/3 that does the job. d) Solve problems a) to c) using difference lists. Cool! Use the predefined function time/1 to compare the solutions. What happens if the same character appears in more than one node. Try for instance pre_in_tree(aba,baa,T).

Problem 69

intermediate

Dotstring representation of binary tree.

We consider again binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. Such a tree can be represented by the preorder sequence of its nodes in which dots (.) are inserted where an empty subtree (nil) is encountered during the tree traversal. For example, the tree shown in problem P67 is represented as 'abd..e..c.fg...'. First, try to establish a syntax (BNF or syntax diagrams) and then write a function tree_dotstring/2 which does the conversion in both directions. Use difference lists.

Multiway Trees

A multiway tree is composed of a root element and a (possibly empty) set of successors which are multiway trees themselves.

  • A multiway tree is never empty.
  • The set of successor trees is sometimes called a forest.

We represent a multiway tree by an expression t(X,F), where X denotes the root node and F denotes the forest of successor trees (a list).

%%{init: {'theme':'neutral'}}%%
    graph TD
        a((a)) --> f((f))
        a --> c((c))
        a --> b((b))
        f --> g((g))
        b --> d((d))
        b --> e((e))

The example tree depicted above is therefore represented by the following expression:

t( a, [ t( f,   [   t( g, [] )  ]),
        t( c,   [               ]),
        t( b,   [   t( d, [] ),
                    t( e, [] )  ]) ])

Problem 70 B

easy

Check whether a given term represents a multiway tree.

Write a function istree/1 which succeeds if and only if its argument is an expressions representing a multiway tree.

Example

istree(
    t( a, [ t( f,   [   t( g, [] )  ]),
            t( c,   [               ]),
            t( b,   [   t( d, [] ),
                        t( e, [] )  ]) ])
) == true

Problem 70 C

easy

Count the nodes of a multiway tree.

Write a function nnodes/1 which counts the nodes of a given multiway tree.

Example

nnodes(t(a,[t(f,[])])) == 2. 

Problem 70

intermediate

Tree construction from a node string.

We suppose that the nodes of a multiway tree contain single characters. In the depth-first order sequence of its nodes, a special character ^ has been inserted whenever, during the tree traversal, the move is a backtrack to the previous level. By this rule, the tree in the figure opposite is represented as: afg^^c^bd^e^^. Define the syntax of the string and write a function tree(String,Tree) to construct the Tree when the String is given. Work with atoms (instead of strings). Make your function work in both directions.

Problem 71

easy

Determine the internal path length of a tree.

We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree. By this definition, the tree in the figure of problem P70 has an internal path length of 9. Write a function ipl(Tree,IPL) for the flow pattern (+,-).

Problem 72

easy

Construct the bottom-up order sequence of the tree node.

Write a function bottom_up(Tree,Seq) which constructs the bottom-up sequence of the nodes of the multiway tree Tree. Seq should be a Prolog list. What happens if you run your function backwords?

Problem 73

intermediate

Lisp-like tree representation.

There is a particular notation for multiway trees in Lisp. Lisp is a prominent functional programming language, which is used primarily for artificial intelligence problems. As such it is one of the main competitors of Prolog. In Lisp almost everything is a list, just as in Prolog everything is a term. The following pictures show how multiway tree structures are represented in Lisp. Note that in the "lispy" notation a node with successors (children) in the tree is always the first element in a list, followed by its children. The "lispy" representation of a multiway tree is a sequence of atoms and parentheses '(' and ')', which we shall collectively call "tokens". We can represent this sequence of tokens as a Prolog list; e.g. the lispy expression (a (b c)) could be represented as the Prolog list ['(', a, '(', b, c, ')', ')']. Write a function tree_ltl(T,LTL) which constructs the "lispy token list" LTL if the tree is given as term T in the usual Prolog notation. Example: ?- tree_ltl(t(a,[t(b,[]),t(c,[])]),LTL). LTL = ['(', a, '(', b, c, ')', ')'. As a second, even more interesting exercise try to rewrite tree_ltl/2 in a way that the inverse conversion is also possible: Given the list LTL, construct the Prolog tree T. Use difference lists.

Graphs

A graph is defined as a set of nodes and a set of edges, where each edge is a pair of nodes.

%%{init: {'theme':'neutral'}}%%
    graph TD
        b((b)) --- c((c))
        b --- f((f))
        g((g)) --- h((h))
        c --- f
        b ~~~ g
        f --- k((k))
        g ~~~ d((d))

There are several ways to represent graphs. One method is to represent each edge separately as one clause (fact). In this form, the graph depicted above is represented as the following list:

[ [h, g], [k, f], [f, b], ... ]

We call this the edge-list form. Obviously, isolated nodes cannot be represented.

Another method is to represent the whole graph as one data object. According to the definition of the graph as a pair of two sets (nodes and edges), we may use the following list to represent the graph above.

 [
    [ b, c, d, f, g, h, k],
    [ [b, c], [b, f], [c, f], [f, k], [g, h] ]
 ]

We call this graph-list form. Note, that the lists are kept sorted, they are really sets, without duplicated elements. Each edge appears only once in the edge list (the second sublist); i.e. an edge from a node x to another node y is represented as [x, y], the list [y, x] is not present.

The graph-list form is our default representation.

A third representation method is to associate with each node the set of nodes that are adjacent to that node. We call this the adjacency-list form. In our example:

[ [b, c, f], [c, b, f], [d], [f, b, c, k], ... ] 

where a sublist [n, d1, d2, ..., dN] states that node n has edges to d1, d2, ... dN.

The representations we introduced so far are lists and therefore well suited for automated processing, but their syntax is not very user-friendly. Typing the terms by hand is cumbersome and error-prone. We can define a more compact and "human-friendly" notation as follows: A graph is represented by a list of nodes and edges X-Y. If an X appears as an endpoint of an edge, it is automatically defined as a node. Our example could be written as:

[b-c, f-c, g-h, d, f-b, k-f, h-g]

We call this the human-friendly form. As the example shows, the list does not have to be sorted and may even contain the same edge multiple times. Notice the isolated node d.

When the edges are directed we call them arcs. These are represented by ordered pairs. Such a graph is called directed graph. To represent a directed graph, the forms discussed above are slightly modified. The example graph opposite is represented as follows. Arc-clause for. arc(s,u). arc(u,r). ... Graph-term for. digraph([r,s,t,u,v],[a(s,r),a(s,u),a(u,r),a(u,s),a(v,u)]. Adjacency-list form [n(r,[]),n(s,[r,u]),n(t,[]),n(u,[r]),n(v,[u]). Note that the adjacency-list does not have the information on whether it is a graph or a digraph.

Human-friendly form [s > r, t, u > r, s > u, u > s, v > u].

Finally, graphs and digraphs may have additional information attached to nodes and edges (arcs). For the nodes, this is no problem, as we can easily replace the single character identifiers with arbitrary compound terms, such as city('London',4711). On the other hand, for edges we have to extend our notation. Graphs with additional information attached to edges are called labelled graphs. Arc-clause for. arc(m,q,7). arc(p,q,9). arc(p,m,5).

Graph-term form. digraph([k,m,p,q],[a(m,p,7),a(p,m,5),a(p,q,9)].

Adjacency-list form [n(k,[]),n(m,[q/7]),n(p,[m/5,q/9]),n(q,[]).

Notice how the edge information has been packed into a term with functor '/' and arity 2, together with the corresponding node.

Human-friendly form [p>q/9, m>q/7, k, p>m/5].

The notation for labelled graphs can also be used for so-called multi-graphs, where more than one edge (or arc) are allowed between two given nodes.

Problem 80

hard

Conversion.

Write functions to convert between the different graph representations.

With these functions, all representations are equivalent; i.e. for the following problems you can always pick freely the most convenient form. The reason this problem is rated "hard" is not because it's particularly difficult, but because it's a lot of work to deal with all the special cases.

Problem 81

intermediate

Paths from one node to another one.

Write a function paths(G,A,B) to find the acyclic paths from node A to node B' in the graph G. The function should return all paths.

Problem 82

easy

Cycles from a given node.

Write a function cycles(G,A) to find the closed paths (cycles) starting at a given node A in the graph G. The function should return all cycles.

Problem 83

intermediate

Construct all spanning tree.

Write a function s_tree(Graph,Tree) to construct (by backtracking) all spanning trees of a given graph. With this function, find out how many spanning trees there are for the graph depicted to the left. The data of this example graph can be found in the file p83.dat. When you have a correct solution for the s_tree/2 function, use it to define two other useful functions: is_tree(Graph) and is_connected(Graph). Both are five-minutes tasks!

Problem 84

intermediate

Construct the minimal spanning tree.

Write a function ms_tree(Graph,Tree,Sum) to construct the minimal spanning tree of a given labelled graph. Hint: Use the algorithm of Prim. A small modification of the solution of P83 does the trick. The data of the example graph to the right can be found in the file p84.dat.

Problem 85

intermediate

Graph isomorphism.

Two graphs G1(N1,E1) and G2(N2,E2) are isomorphic if there is a bijection f: N1 -> N2 such that for any nodes X,Y of N1, X and Y are adjacent if and only if f(X) and f(Y) are adjacent. Write a function that determines whether two graphs are isomorphic. Hint: Use an open-ended list to represent the function f.

Problem 86

intermediate

Node degree and graph coloration.

  1. Write a function degree(Graph,Node,Deg) that determines the degree of a given node.
  2. Write a function that generates a list of all nodes of a graph sorted according to decreasing degree.
  3. Use Welch-Powell's algorithm to paint the nodes of a graph in such a way that adjacent nodes have different colors.

Problem 87

intermediate

Depth-first order graph traversal (alternative solution).

Write a function that generates a depth-first order graph traversal sequence. The starting point should be specified, and the output should be a list of nodes that are reachable from this starting point (in depth-first order).

Problem 88

intermediate

Connected components (alternative solution).

Write a function that splits a graph into its connected components.

Problem 89

intermediate

Bipartite graph.

Write a function that finds out whether a given graph is bipartite.