简体   繁体   中英

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.

I changed my toString method to MakeString , because I thought it was getting confused when converting comparable type data to a string. 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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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