我在网站上发现了二进制搜索树插入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。
为什么会这样?
答案 0 :(得分:3)
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
。
答案 1 :(得分:0)
就像其他人已经指出的那样,您每次插入元素时都需要更新root
。
只需return
根的值,并更新树的全局root
。
Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else
root.right = insertRec(root.right, key);
return root;
}
最后,更新您的全局root
。
tree.root = tree.insert(50);
tree.root = tree.insert(20);
完整代码:
class BinarySearchTree {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Node root;
BinarySearchTree() {
root = null;
}
Node insert(int key) {
return insertRec(root, key);
}
/* A recursive function to insert a new key in BST */
Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else
root.right = insertRec(root.right, key);
return root;
}
// Driver Program to test above functions
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.root = tree.insert(50);
tree.root = tree.insert(20);
System.out.println(tree.root.key);
}
}
答案 2 :(得分:0)
/* A recursive function to insert a new key in BST */
void insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
}
}
它称为“阴影效果”。
这意味着您父类的根注释在方法中被根节点所遮盖。 要修复它,请使用“ this.root”引用父类并初始化该对象。
更多信息:阅读文章中的“ Shadowing”。解释得很好。
答案 3 :(得分:-1)
在构造函数中,您无需初始化rootNode。您的密钥也不会在节点中转换,并且您不会将插入的节点设置为左节点或右节点。同样,对于与所遍历的当前节点相同的节点,您也不做任何事情。