简体   繁体   English

为单独的类文件编写方法

[英]writing a method for a seperate class file

I have a .class file named UBT.class (which i do not have access to the source code). 我有一个名为UBT.class的.class文件(我无法访问源代码)。 I need to retrieve data from the UBT.class file. 我需要从UBT.class文件中检索数据。 I have access to methods such as .getRoot() & .getLeft() & .getRight() from the UBT class (Not using the methods from the TreeNode class). 我可以从UBT类访问诸如.getRoot()&.getLeft()&.getRight()之类的方法(不使用TreeNode类中的方法)。

I tried writing an inOrder traversal method using recursion like this but its giving me errors like below although i specifiy it to be UBT not TreeNode 我尝试使用像这样的递归编写inOrder遍历方法,但是它给了我以下错误,尽管我指定它是UBT而不是TreeNode

Error: incompatible types: TreeNode cannot be converted to UBT 错误:类型不兼容:TreeNode无法转换为UBT

//From main method

     public static void inOrder(UBT root)
      {
        if(root.getRoot() != null)
        {
          inOrder(root.getRoot().getLeft());
          System.out.println(root.getRoot().getData() + " ");
          inOrder(root.getRoot().getRight());
        }
      }

class TreeNode
{
  private int data;
  private TreeNode left, right;

  public TreeNode(int data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }

  public int getData() {
    return data;
  }

  public void setData(int newData){
    this.data = newData;
  }

  public TreeNode getLeft() {
    return left;
  }

  public TreeNode getRight() {
    return right;
  }

  public void setLeft(TreeNode left) {
    this.left = left;
  }

  public void setRight(TreeNode right) {
    this.right = right;
  }
}

class BST // Typical BST implementation

It looks like you want to split it up so your main recursion is on TreeNodes, not the UBT object. 看来您想将其拆分,因此您的主要递归位于TreeNodes而不是UBT对象上。

  public static void inOrder(TreeNode node) {
    if(node != null)
    {
      inOrder(node.getLeft());
      System.out.println(node.getData() + " ");
      inOrder(node.getRight());
    }
  }

  public static void inOrder(UBT root) {
    if (root.getRoot() != null) {
      inOrder(root.getRoot());
    }
  }

Using this, you'd call inOrder with your UBT, then it would grab the root TreeNode and do recursion on that with the TreeNode version of inOrder. 使用此方法,您可以使用UBT调用inOrder,然后它将获取根TreeNode并使用inOrder的TreeNode版本对此进行递归。

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

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