Homework Solution

Trees

Problems to be Submitted (20 points)

  1. (5 points)

    3, 1, +, 3, x, 9, 5, -, 2, +, /, 3, 7, 4, -, x, 6, +, -

  2. (5 points)

  3. (5 points)

                 A
                / \
             __/   \___
            /          \
           B           G
          / \         / \
         C   D       H   K
            / \     / \
           E   F   I   J
    

  4. (5 points)

    (image missing)

  5. (extra credit)

    We can solve the problem in O(n) time using recursion. We design a recursion on subtrees of the full tree that will simultaneously return two pieces of information: (1) the height of the subtree, and (2) the diameter of the subtree.

    As a base case, a height with a single node has a trivial height of 0 and diameter of 0. For the general case, we have already seen that the height of a node is one greater than the maximum height of its subtrees. To understand the diameter of a subtree, we consider whether a longest path within that subtree goes through the root of the subtree. If so, then we consider two subcases. If the root has only one child, then the longest path must go from the root to the deepest leaf of that subtree, and thus have height 1 + h, where h is the height of the one child's subtree. If the root has two or more children, then the longest path must be 2 + h + h' where h and h' are the two greatest heights of all the childrens' subtrees.

    If the longest path of the considered subtree does not go through its root, then it must stay entirely within one of its subtrees, and in that case, the diameter of the bigger tree is equal to the maximum diameter of any of its subtrees.

    So to determine the diameter of a subtree within the recursion, we compute the maximum of all its subtree's diameters and 1+h or 2+h+h' where h is the maximum height subtree, and h' is the second greatest height subtree if there are two or more children.


Last modified: Sunday, 15 November 2015