0

I'm learning data structures, and I'm building an AVL tree class. I want to traverse the tree by saving the elements in one string. I already built the three functions that traverse over the tree in {inorder,preorder,postorder} recursively on the console. I wonder how I can modify the code to load the result into a string, and not the console.

I will post the code for postorder down here:

void printPostorder(Node root) { // prints the tree in post order     left right root
    if (root == null)
        return;
    printPostorder(root.left);
    printPostorder(root.right);
    System.out.print(root.element + " ");
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

0

I don't know how you made your printPostorder or printPostorder but you could use a string builder

StringBuilder str = new StringBuilder();
// you might want to do this recursively or with a loop though
str.append(printPostorder(root.left).toString);
str.append(printPostorder(root.right).toString);

Also for something more interesting, see How to print binary tree diagram in Java?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Saheed
  • 301
  • 1
  • 2
  • 11