【问题标题】:Binary Search Tree: Recursive toString二叉搜索树:递归 toString
【发布时间】:2021-05-05 21:03:23
【问题描述】:

它只打印出一项。 假设按升序打印树的内容

public String toString()
{
    return toString (_root);
}
private String toString(BSTnode root)
{
    if (root == null)
        return "";
    toString(root._left);
    toString(root._right);
    return root._data.toString();
}

【问题讨论】:

    标签: java recursion binary-tree


    【解决方案1】:

    你想如何展示它们?

    例如,您需要附加字符串。

    private String toString(BSTnode root)
    {
        StringBuilder builder = new StringBuilder();
        if (root == null)
            return "";
        builder.append(toString(root._left));
        builder.append(toString(root._right));
        return builder.append(root._data.toString()).toString();
    }
    

    或者只是在字符串上使用串联。

    private String toString(BSTnode root)
    {
        String result = "";
        if (root == null)
            return "";
        result += toString(root._left);
        result += toString(root._right);
        result += root._data.toString()
        return result;
    }
    

    【讨论】:

    • 如何在字符串中的每个字符后添加逗号?即“a,b,c,d,e,f”
    【解决方案2】:
    //Helper
    
    public String toString(){
    return "<" +toString(root) + ">";
    }
    
    //recursively printing out the nodes
    
    public static String toString(Node r){
    if(r==null)
    return "";
    else
    return toString(r.left) + " " +r.value + " " +toString(r.right);
    }
    

    【讨论】:

      【解决方案3】:
      public class TreeNode {
          int val;
          TreeNode left;
          TreeNode right;
      
          TreeNode(int x) {
              val = x;
          }
      
          // Helper
      
          public String toString() {
              return "<" + toString(this) + ">";
          }
      
          // recursively printing out the nodes
      
          public static String toString(TreeNode r) {
              if (r == null)
                  return "";
              else
                  return r.val + " " + toString(r.left) + " " + toString(r.right);
          }
      
      }
      

      【讨论】:

        【解决方案4】:
        public String toString(){
            return toString (_root);
        }
        
        public String toStringAscending(BSTnode node)
        {
            if (node == null) return "";
            return toStringAscending(node.left) + node._data.toString() + toStringAscending(node.right);
        }
        

        【讨论】:

          猜你喜欢
          • 2016-08-22
          • 2014-01-02
          • 2021-07-03
          • 2019-04-17
          • 1970-01-01
          • 1970-01-01
          • 2013-04-14
          • 1970-01-01
          • 2017-05-08
          相关资源
          最近更新 更多