【问题标题】:toString() method and recursiontoString() 方法和递归
【发布时间】:2013-08-09 22:45:25
【问题描述】:

我正在创建一个使用二叉搜索树实现通用Set 的类。我正在实现我的 toString() 方法,以便它显示一个括号表达式,但我无法让它工作。例如,这是一个基本的二叉树:

我希望我的 toString 方法输出这个二叉树:

(10 (5 (4 () ())   (6 () ()))   (20 (15 () ())   (25 () ())))

() 表示一棵空树。

这是我使用 toString 方法的类。任何帮助表示赞赏!

// Allow short name access to following classes
import csc143.data_structures.*;

public class MySet<E> implements SimpleSet<E> {

  // the root of the "tree" that structures the set
  private BTNode root;
  // the current number of elements in the set
  private int numElems;

  public MySet() {
    root = null;

    numElems = 0;
  }

  /**
   * Add an element to the set. 
   * 
   * @param e The element to be added to the set.
   * @return  <tt>true</tt> If this operation updated the contents of the set.
   */
  public boolean add(E e) {
    try {
      root = addToSubtree(root, (Comparable) e);
      return true;
    } catch(DuplicateAdded exc) {
      // duplicate trying to be added
      return false;
    }

  }

  // This helper method adds the element "e" to tree rooted at r. Returns
  // (possibly new) tree containing "e", or throws DuplicateAdded exception
  // if "e" already exists in tree.
  private BTNode addToSubtree(BTNode r, Comparable elem)
    throws DuplicateAdded {
    if(r == null) {
      numElems++;
      return new BTNode(elem);
    }

    int compare = elem.compareTo(r.item);
    // element already in tree
    if(compare == 0) {
      throw new DuplicateAdded();
    } else if(compare < 0) {
      r.left = addToSubtree(r.left, elem);
    } else {  // compare > 0
      r.right = addToSubtree(r.right, elem);
    }

    // element has been added
    return r;
  }

  /**
   * Remove all elements from this set.
   */
  public void clear() {
    root = null;

    numElems = 0;
  }

  /**
   * Checks for the existance of the specified value within the set.
   * 
   * @param e The value sought.
   * @return  <tt>true</tt> If the value exists in the set.
   */
  public boolean contains(E e) {
    return subtreeContains(root, (Comparable) e);
  }

  // This helper method returns whether element "elem" is in
  // (sub-)tree with root "r".
  private boolean subtreeContains(BTNode r, Comparable elem) {
    if(r == null) {
      return false;
    } else {
      int compare = elem.compareTo(r.item);
      // found element
      if(compare == 0){
        return true;
      } else if(compare < 0) {
        return subtreeContains(r.left, elem);
      } else {  // compare > 0
        return subtreeContains(r.right, elem);
      }

    }

  }

  /**
   * Check for the existance of elements in the set.
   * 
   * @return  <tt>true</tt> If there are no elements in the set.
   */
  public boolean isEmpty() {
    return root == null;
  }

  /**
   * Return the number of elements in the set.
   * 
   * @return The number of elements in the set.
   */
  public int size() {
    return numElems;
  }

  /**
   * Returns a String representation of the contents of the set.
   * 
   * @return  The String representation of the set.
   */
  public String toString() {
    return subtreeToString(root);
  }

  private String subtreeToString(BTNode r) {
    String str = "";
    if(r == null) {
      str += "() ";
      return str;
    } 

    str += "(" + r.item;
    str += subtreeToString(r.left) + 
      subtreeToString(r.right) + ")";

    return str;
  }

  // this inner class creates the node that compose the binary tree structure
  class BTNode<E> {

    /**
     * The item stored in the node.
     */
    public E item;

    /**
     * The node to the left of "this" node.
     */
    public BTNode left;

    /**
     * The node to the right of "this" node.
     */
    public BTNode right;

    /**
     * Constructs the BTNode object (three parameters).
     * 
     * @param item The item to be stored in the node.
     * @param left The node to the left of "this" node.
     * @param right The node to the right of "this" node.
     */
    @SuppressWarnings("unchecked")
    public BTNode(Object item, BTNode left, BTNode right) {
      // bind to references
      this.item = (E) item;
      this.left = left;
      this.right = right;
    }

    /**
     * Constructs the BTNode (one parameter).
     * 
     * @param The item to be stored in the node.
     */
    public BTNode(Object item) {
      // call three parameter constructor
      this(item, null, null);
    }

  }

}

【问题讨论】:

    标签: java recursion binary-tree tostring


    【解决方案1】:

    我在尝试运行代码时遇到了一些问题,但假设所有问题都已解决 - 以下对我有用:

    private String subtreeToString(BTNode r) {
        String str = "";
        if(r == null) {
            return str;
        }
        str += r.item;
        str += " (" + subtreeToString(r.left) + ") (" + subtreeToString(r.right) + ")";
        return str;
    }
    

    输出:

    10 (5 (4 () ()) (6 () ())) (20 () (25 () ()))
    

    (上面提供的示例输出中还有一个错误 - 应在 6 的子级之后添加右括号)

    【讨论】:

    • 谢谢,刚刚修好了。
    • 当我将整数 1 和 2 相加时,我应该得到(1 () (2 () ()))。但是,我收到了1 (()) (2 (()) (()))...
    • 我的猜测是,当r 为空时,您返回() - 因此是双空括号。并再次检查我的实现 - 你不应该在根之前得到一个左括号。如果您愿意,您应该将我的实现从:str += r.item; 更改为:str += "("+r.item; str += " (" + subtreeToString(r.left) + ") (" + subtreeToString(r.right) + "))";
    • 我想通了。你基本上已经有了它,只是删除了几个括号并在r.item 之前包含一个括号。我用修改编辑了我的代码。感谢您的帮助!
    • 我对 toString 方法中的间距有疑问。例如,现在我正在打印:(1 () (2 () (3 () () ))。但是,我试图得到这个:(1 () (2 () (3 () ()))。因此,我希望在不属于空树表示的右括号之前没有空格:())。我已经尝试了很多事情,但似乎无法在不为不需要的部分添加或删除空间的情况下使其工作。我想我需要一种方法来确定右括号是否会跟随一个空树表示,以便不给空间。我上面的代码是用我最新的改进编辑的。
    猜你喜欢
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多