有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java实现二叉树而不使用预定义函数

我想实现一个二叉树,但我在传递一个方法时遇到了麻烦。这是我的代码: 有两个独立的类:xyzBTree。{}的方法正在{}的方法{}中使用

class xyz{    //main class
    public static void main (String args[]){
    xyz obj = new xyz();
    obj.test(n);    //takes input (int) from user
    }

    public void test(int n){
        BTree p = new BTree();
        int d1 = p.depth(    //I want ot pass a node here);
            //My question: How to pass an argument here as "Node" to be received properly by the method??
        ....
        ....
    }
}
class BT Tree{     //another different class
    private Node root;
    private Node node;
    private int size;
    public static class Node {
        Node left;
        Node right;
        Node back;
        int data;
        int index;

    Node(int newindex) {
        left = null;
        right = null;
        back= null;
        data = 0;
        index = newindex;
    }
}
    public void BTree() {  //constructor
        root = null;
    }

    public int depth(Node node){     //Node pass will be correctly executed here
        if (node.index==root.index)
            return 0;
        else 
            return 1+depth(parent(node));
    }
}

我的问题是:如何通过depth()方法传递节点


共 (1) 个答案

  1. # 1 楼答案

    My Question is: how to pass a Node through depth() method?

    尚不清楚BTree类的设计是否旨在隐藏Node对象

    • 如果不打算隐藏Node对象,那么答案是“您传递它就像传递任何其他对象引用一样”。这就引出了一个问题:节点引用从何处获得,答案是BTree类必须提供允许外部代码(例如xyz类)获取节点引用的方法。这还意味着depth方法需要考虑Node不是“this”BTree成员的可能性。。。现在

    • 如果打算隐藏Node对象,那么depth(Node)方法中存在问题

      • 如果外部调用代码无法获取Node,那么将其作为公共方法有什么意义呢。它应该是一种私有方法吗
      • 它应该是一个公共方法,但语义不同吗?例如,它应该给出树中任何节点的最大深度,而不是给定节点的深度吗?(注意:depth()的实现需要完全不同……)