Search code examples
javarecursionbinary-treeascii-art

Recursively generate an ASCII binary tree


Here is a picture of what my code needs to do.

Before Call:

            +----+
            | -9 |
            +----+
           /      \
          /        \
      +----+      +----+
      |  3 |      | 15 |
      +----+      +----+
     /           /      \
    /           /        \
+----+      +----+      +----+
|  0 |      | 12 |      | 24 |
+----+      +----+      +----+
           /      \
          /        \
      +----+      +----+
      |  6 |      | -3 |
      +----+      +----+

After Call:

            +----+
            | -9 |
            +----+
           /      \
          /        \
      +----+      +----+
      |  6 |      | 30 |
      +----+      +----+
     /           /      \
    /           /        \
+----+      +----+      +----+
|  0 |      | 24 |      | 48 |
+----+      +----+      +----+
           /      \
          /        \
      +----+      +----+
      | 12 |      | -3 |
      +----+      +----+

Basically this problem requires that I double all data values greater than 0 in a binary tree of integers. My code below does this for a few values but stops early. I am not sure how to fix this recursively. This is what my output looks like for the tree given above.

       overallRoot
         _[-9]_______________
        /                    \
    _[6]                 _____[30]
   /                    /         \
[0]                _[12]           [24]
                  /     \
               [6]       [-3]
public void doublePositives() {
    doublePositives(overallRoot);
}

private IntTreeNode doublePositives(IntTreeNode root) {
    if (root != null) {
        if (root.data > 0) {
            root.data = 2 * root.data;
        } else {
            root.left = doublePositives(root.left);
            root.right = doublePositives(root.right);
        }
    }
    return root;
}

Solution

  • You still need to traverse the tree if you are doubling a node. Drop the else so that you always traverse. Also, I've removed the assignments because you are not changing the tree structure:

    if(root != null) {
        if(root.data > 0) {
            root.data = 2 * root.data;
        }
        doublePositives(root.left);
        doublePositives(root.right);
    }