1

I have a simple function to recursively build a tree of strings. The function is given a string "***" and the tree that results should look like this:

                                        ***
                                 /       |       \
                              X**       *X*       **X
                             / \        / \        / \
                          XX*  X*X    XX* *XX    X*X  *XX 
                          /     \     /     \     /     \
                         XXX   XXX   XXX   XXX   XXX    XXX

The problem is that my function is only creating the farthest left side of the tree (X**, XX*, XXX)

Here is the function:

//Takes in the string "***"
void buildTree(string tree){
 if (tree == "XXX") return;
 else{
   string newTree;
   for (int i=0; i<tree.size(); i++){
     if(tree[i] == '*'){
       newTree = tree;
       newTree[i] = 'X';
       cout << newTree << endl;
       return buildTree(newTree);
     }
   }
 }
}
1
  • I indented the code correctly. Maybe you are now able to spot the error more easily Commented Oct 11, 2013 at 0:20

1 Answer 1

1

Remove 'return' from "return buildTree(newTree);" and you should be good to go.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.