[英]Java Binary Search Tree implementation problem.!
我正在用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中只有按值傳遞。 除了在第一種情況下,我將新創建的根傳遞給它之外,在每種情況下我都將根作為null。 在這里,當我通過傳遞根的左邊或右邊的值來對插入函數進行遞歸調用時,則在新調用中,如果需要它,則會創建新的根,但是當函數移開時,不會反映出它的值調用方函數的變量。 簡而言之,問題是由於java后面跟着按值調用。
誰能為這個問題提出解決方案?
您對insert(root.right/left, d)
調用不會更改原始的右/左節點(如果它們為null),而只是使方法參數指向一個新變量(正如您所注意到的,在Java中不會更改原始參考)。 對第一個根的更改有效,因為您調用了另一個方法insert(int)
。
您是否考慮過制作左右BinaryTree
而不是Node
? 另外,不要使用“空”,而應考慮使用“空” BinaryTree(具有空根和isEmpty
方法)。
請注意, 從概念上講 ,左和右是樹,而不是節點,因此設計會更簡潔。
示例代碼。 未經測試,但想法應該是正確的:
class Node {
BinaryTree left, right;
Integer data;
Node(Integer d, BinaryTree left, BinaryTree right) {
this.data = d;
this.left = left;
this.right = right;
}
}
class BinaryTree {
Node root;
// Empty tree
BinaryTree() {
this(null);
}
BinaryTree(Node root) {
this.root == root;
}
void insert(int d) {
if (this.root == null) {
// The tree was empty, so it creates a new root with empty subtrees
this.root = new Node(d, new BinaryTree(), new BinaryTree());
} else if (d > this.root.data) {
this.root.right.insert(d);
} else if (d < this.root.data) {
this.root.left.insert(d);
}
}
}
筆記:
建議,
int
值,則不會使用Integer
。 我將發布任何人都可以復制的最簡單的單元測試,以及如果沒有任何意義的調試器,您將在此處看到。
這並不能真正回答您的問題,但是評論太久了。 ;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.