-2

I am a beginner. I am trying to print an avl tree level by level and it should be from right to left. but the result from left to right. I hope you can solved my problem. Here is the piece of my source code:

void printOrder( TreeNode *treePtr, int *row) {
    if(treePtr != NULL){
        (*row)++;
        printOrder(treePtr->rightPtr,row);
        int i;
        for(i=0;i<(*row);i--)
            printf("\t");
        printf("%d\n", treePtr->data);
        printOrder(treePtr->leftPtr,row);
        (*row)--;
    }
}

void printTree( TreeNode *treePtr) {
    int row = 0;
    printOrder(treePtr,&row);
}

The result:

           80
     70
50
     40
           30

The result that i want should be like this:

       30\
            40\
                50
            70/
        80/
cwschmidt
  • 1,136
  • 11
  • 16

1 Answers1

0

You could first traverse your tree (as you do already) and add every entry to a std::vector instead of printing it directly, resulting in a sequence of elements like

{80,70,50,40,30}

and then your reverse the content of the vector resulting in

{30,40,50,70,80}

Now print that content in that form you desire, by just looping over the vector.

To get the correct intendation, you can store std::pair elements in the vector, containing the intendation level as the second element e.g.

{{80,0},{70,1},{50,2},{40,1},{30,0}}

For printing intendation you substract the number from the maximum level of intendation.

Or, alternatively, traverse your tree in the left-middle-right order by exchanging the lines

printOrder(treePtr->rightPtr,row);

and

printOrder(treePtr->leftPtr,row);

and print it as desired.

cwschmidt
  • 1,136
  • 11
  • 16
  • how if i want to print it directly? – Michael Loew Nov 26 '16 at 04:48
  • @Michael Loew As I suggested in my last sentence: Traverse the tree in left-middle-right order by exchanging the following lines `'printOrder(treePtr->rightPtr,row);'` and `'printOrder(treePtr->leftPtr,row);'` – cwschmidt Nov 26 '16 at 16:15