4

The following question appeared on a test my instructor gave a couple of years ago. He provided an answer, but did not provide a satisfactory explanation. I have googled this topic, but I didn't find much. I was hoping that the community could help me understand this concept.

In order to find the sum of all of the integers in a binary tree, what type of traversal would be used?

(A) breadth-first
(B) depth-first in-order
(C) depth-first post-order
(D) depth-first pre-order

My instructor says that the answer is (C) depth-first post-order, but I don't understand why. It seems like they would all work. I would appreciate any insight that you might have.

Thanks.

Edit: I finally figured how why my instructor thought the answer was (C).

If you were to write a sum function with the addition all in a single statement such as:

    int addup(Node n)
    {
        if (n == nil) return 0;
        return addup(n.left) + n.value + addup(n.right);
    }

The traversal would be post-order regardless of the order of the terms in the sum. This is because the two functions are evaluated first before the addition occurs. It is, however, trivial to force a pre-order or in-order traversal as Keith Randall showed in his answer.

Ian
  • 348
  • 1
  • 2
  • 11

1 Answers1

3

Any traversal order would work, as sum is associative and symmetric. For example, depth-first in-order:

int addup(Node n) {
    if (n == nil) return 0;
    int sum = addup(n.left);
    sum += n.value;
    sum += addup(n.right);
    return sum;
}

All the traversals admit an easy sum implementation.

Keith Randall
  • 22,985
  • 2
  • 35
  • 54