java实现二叉树而不使用预定义函数
我想实现一个二叉树,但我在传递一个方法时遇到了麻烦。这是我的代码:
有两个独立的类:xyz
和BTree
。{
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 楼答案
尚不清楚
BTree
类的设计是否旨在隐藏Node
对象如果不打算隐藏
Node
对象,那么答案是“您传递它就像传递任何其他对象引用一样”。这就引出了一个问题:节点引用从何处获得,答案是BTree
类必须提供允许外部代码(例如xyz
类)获取节点引用的方法。这还意味着depth
方法需要考虑Node
不是“this”BTree
成员的可能性。。。现在如果打算隐藏
Node
对象,那么depth(Node)
方法中存在问题Node
,那么将其作为公共方法有什么意义呢。它应该是一种私有方法吗李>depth()
的实现需要完全不同……)李>