【问题标题】:How to deal with public/private pair in this binary trees?如何处理此二叉树中的公共/私有对?
【发布时间】:2014-10-10 09:25:18
【问题描述】:

问题是要向这个类添加一个方法,该方法从扫描仪中读取数据,并使用来自扫描仪的数据以预排序方式构造一棵树。

//the class to add the method readTree to
public class IntTree {
private IntTreeNode overallRoot;
...
}

这是我的解决方案(我的所有逻辑都已关闭,但公共私有对有问题)

    public void readTree(Scanner s){
    overallRoot = readTree(s);
}
private IntTreeNode readTree(Scanner s){
    int type = s.nextInt();
    IntTreeNode root = new IntTreeNode(s.nextInt());
    if(type % 2 == 1){
        root.left = readTree(s);
    }
    if(type==2 || type==3){
        root.right= readTree(s);
    }
    return root;
}

我们的风格(通常也是)是对二叉树使用公共/私有方法方法。那就是利用 x=change(x)。公共方法的返回类型应该是 void(给定方向)。由于返回 change(x) 部分,私有助手的返回类型是 IntTreeNode。我的问题是你将如何陪伴我设定的公共/私人对的方向,即编写私人助手的方法签名。对于我当前的代码,编译器给了我一个重复的方法(我希望 bc 两者具有相同的方法签名。我想过引入一些任意参数并将其设置为 null 但认为这是不好的风格。与其他问题不同,你不'不需要将 int 树节点作为参数传递,因为您不使用现有数据,而是从头开始构建它

【问题讨论】:

  • 我会将第二种方法重命名为其他名称。 “populateTree()”也许。那么没有重复方法的机会。
  • 是的,行得通。我什至没有想到这种方法

标签: java private public


【解决方案1】:

我认为最直接的方法是将私有方法命名为稍微不同的名称,也许

private IntTreeNode readTreeRecursive(Scanner s)

private IntTreeNode readTreeInternal(Scanner s)

你有什么理由不能做这样的事情吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-04
    • 2021-09-17
    • 2021-02-16
    • 1970-01-01
    • 2021-04-10
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多