Kalmar
Kalmar

Reputation: 195

non-binary tree using recursion is not creating entire tree

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);
     }
   }
 }
}

Upvotes: 1

Views: 283

Answers (1)

X.J
X.J

Reputation: 662

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

Upvotes: 1

Related Questions