简体   繁体   English

如何以字符串方法打印树的数据?

[英]How can I print the data of a tree in a string method?

I have this method that prints the contents of the Avl tree .我有这种打印Avl 树内容的方法。

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.仍然会有一个问题,在这种情况下,您将返回 Avl 树的一个节点,而我需要 Avl 树中的所有节点 I don't want to use some kind of void method我不想使用某种 void 方法在此处输入图像描述

You need to add the result of the recursion to Str .您需要将递归结果添加到Str like so: Str += traversInOrder(node.left) and the same goes for the right one.像这样: Str += traversInOrder(node.left)右边的也是如此。 You also should print the content of the node with node.value or whatever your content value name is.您还应该使用node.value或任何您的内容值名称来打印节点的内容。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM