我正在開發一個在java中的二叉搜索樹。但是我面臨着一些困難。下面是代碼Java二叉搜索樹實現問題。
class Node {
Node left, right;
Integer data;
Node(Integer d, Node left, Node right) {
this.data = d;
this.left = left;
this.right = right;
}
}
class BinaryTree {
Node root;
public BinaryTree(Node root) {
this.root = root;
}
void insert(int d)
{
if(root==null)
root= new Node(d, null, null);
insert(root,d);
}
void insert(Node root, int d) {
if (root == null) {
root=new Node(d,null,null);
} else if (d > root.data) {
insert(root.right, d);
} else if (d < root.data) {
insert(root.left, d);
}
}
void inorder(Node root) {
if (root != null) {
inorder(root.left);
System.out.println(root.data);
inorder(root.right);
}
}
}
public class BST {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
BinaryTree bt=new BinaryTree(null);
while (!(str = br.readLine()).equalsIgnoreCase("0")) {
bt.insert(Integer.parseInt(str));
}
bt.inorder(bt.root);
}
}
我面對這裏的問題是,在Java中只按值傳遞。除了第一個將新創建的根傳遞給它的第一種情況外,我在每種情況下都將root設置爲null。在這裏,當我通過傳遞根值的左邊或右邊的值來對插入函數進行遞歸調用,然後在新的調用中,如果需要創建新的根,但是當函數結束時,它的值不會被反映到調用者函數的變量。 總之,這個問題是由於Java所遵循的值的調用。
任何人都可以請建議解決這個問題?
你的問題在於你試圖「改變」null值 – WuHoUnited 2012-02-25 18:05:22
你也知道你的第一個插入方法試圖插入d兩次嗎? – WuHoUnited 2012-02-25 18:11:57