我在网站上找到了二进制搜索树插入Java代码,
https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/
部分代码如下
if (root == null) {
root = new Node(key);
return root;
}
而且我认为我们不需要任何return语句,因为root本身就是引用类型(节点),因此更新root就足够了。
所以我改变了这样的代码。
class BinarySearchTree {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Node root;
BinarySearchTree() {
root = null;
}
void insert(int key) {
insertRec(root, key);
}
/* A recursive function to insert a new key in BST */
void insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
}
if (key < root.key)
insertRec(root.left, key);
else if (key > root.key)
insertRec(root.right, key);
}
// Driver Program to test above functions
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.insert(50);
tree.insert(20);
System.out.println(tree.root);
}
}
但是tree.root返回null。
为什么会这样呢?
最佳答案
root = new Node(key);
更新局部变量,它不更新树的根(this.root
),也不应该。因此,此分配不会更新树。
当您返回新创建的Node
时(就像您更改的原始代码所做的那样),您可以将其分配为树的根(就像原始代码对root = insertRec(root, key);
所做的一样)或左或右子级现有树节点的名称(如原始代码使用root.left = insertRec(root.left, key);
或root.right = insertRec(root.right, key);
所做的那样)。这就是树的更新方式。
编辑:Java是按值传递语言,而不是按引用传递。当您将变量传递给方法时,该方法无法更改所传递变量的值。如果将值null
的变量传递给方法,并且该方法为其分配了一个值,则该方法返回后,该变量仍将包含null
。
关于java - 二进制搜索树tree.root返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52849376/