简体   繁体   English

二进制搜索树的遍历方法,以toString

[英]Binary search tree traversal method, in order toString

I made a binary search tree from scratch with my own nodes which functions perfectly when I add nodes and when I print the tree in order to the console. 我使用自己的节点从头开始构建了一个二进制搜索树,当添加节点以及将其打印到控制台时,该搜索树可以完美运行。 However, I'm having a time and a half getting the toString method working. 但是,我花了一半时间使toString方法正常工作。

I changed my toString method to MakeString , because I thought it was getting confused when converting comparable type data to a string. 我将toString方法更改为MakeString ,因为我认为将可比较的类型数据转换为字符串时会感到困惑。 I can either get the method to return one node or just in object form, but never the whole tree in string form. 我既可以获取返回一个节点的方法,也可以仅返回对象的形式,但不能以字符串形式返回整个树。 The printInOrder() method works perfectly, so why won't my MakeString() method? printInOrder()方法可以完美地工作,为什么我的MakeString()方法不起作用?

public void printInOrder(){

    if (left != null) left.printInOrder();

     System.out.println(data);

    if (right != null) right.printInOrder();
}

public String MakeString(){

    String OrderedTree;
    StringBuilder sb = new StringBuilder();
    if (data == null) return "Tree is empty";

    if (left != null) left.MakeString();

     sb.append(data);

    if (right != null) right.MakeString();

If you need something to be preserved throughout the recursion, then it should be passed as a parameter. 如果您需要在整个递归中保留某些内容,则应将其作为参数传递。 This will often result in a pair of methods if you want to avoid having to prep the initial call or otherwise have something to do before or after the recursion. 如果您要避免必须准备初始调用或在递归之前或之后要做其他事情,这通常会导致使用一对方法。

In your case you are using a StringBuilder which needs to be created before the recursion, preserved throughout, and then used afterward. 在您的情况下,您使用的是StringBuilder ,它需要在递归之前创建,保留并在以后使用。

Ex: 例如:

public String MakeString() {
   if (data == null)
      return "Tree is empty";

   StringBuilder sb = new StringBuilder();

   MakeString(sb);

   return sb.toString();
}

private void MakeString(StringBuilder sb) {
   if (left != null)
      left.MakeString(sb);

   sb.append(data);

   if (right != null)
      right.MakeString(sb);
}

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

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