Home > Enterprise >  How can I print the data of a tree in a string method?
How can I print the data of a tree in a string method?

Time:12-11

I have this method that prints the contents of the Avl tree.

public String traverseInOrder() {
      return traverseInOrder(root);
}

private String traverseInOrder(TNode<T> node) {
  String Str = "";
    if (node != null) {
      if (node.left != null)
        traverseInOrder(node.left);
        Str  =node;
      if (node.right != null)
        traverseInOrder(node.right);
    }
  return Str;
} 

There will still be a problem that in this case you are returning one node of the Avl tree and I need all the node in the Avl tree. I don't want to use some kind of void method enter image description here

CodePudding user response:

You need to add the result of the recursion to Str. like so: Str = traversInOrder(node.left) and the same goes for the right one. You also should print the content of the node with node.value or whatever your content value name is.

Example:

private String traverseInOrder(TNode<T> node) {
  String Str = "";
    if (node != null) {
      if (node.left != null)
        Str  = traverseInOrder(node.left);
      Str  = node.value;
      if (node.right != null)
        Str  = traverseInOrder(node.right);
    }
  return Str;
} 

CodePudding user response:

public String traverseInOrder() {       
    return traverseInOrder(root);
}
private String traverseInOrder(TNode<T> node) {
     String Str = "";
     if (node != null) {
            if (node.left != null)
                Str =traverseInOrder(node.left);
            Str =node;          
            if (node.right != null)
                Str =traverseInOrder(node.right);
    }
    return Str;
}
  • Related