1

With the following recursive code to count leaf nodes of a binary tree, is there any way to make it faster or parallel-computing optimized in time?

Python code - (mag(P) = number of leaf nodes of tree P depth H, left(P) = produces left subtree and right(P)= produces right subtree, not given here, reduce the tree P to subtrees until terminal nodes are reached):

temp = 0
def mag(P):
    global temp
    if len(P) == 0:  #counts the one terminal node
        return temp+1
    elif len(P) == 1:   #counts the two terminal nodes
        return temp+2
    elif len(P) >= 2:
        return mag(left(P)) + mag(right(P))
Ten
  • 119
  • 2

1 Answers1

0

Store the tree in an array $A$ so that $A_i$ contains the index of the parent's node. For example:

A = [-1 0 1 1]

would be a four-node-tree where the root node has one child and that child in turn has two children. The root node has no parent, denoted by -1.

Now go through all array elements in parallel. For every element, increase a counter if its value is not marked and mark the value. The counter now contains the number of non-leaf nodes and its trivial to get the number of leaf nodes from that. Python pseudo code:

A = array of length N
M = [False] * N
cnt = 0
parfor e in A:
    if e >= 0 and not M[e]:
        M[e] = True
        cnt += 1
n_leaves = N - cnt

The parfor keyword stands for "parallel for" and runs its loop body in $O(\log n)$ time (well-known result). This is probably as fast as it gets.