[英]BinaryTree implementation
我想在Java中实现二叉树,并且节点有问题。问题是我无法在根节点中保存newN。 每当我尝试插入一个新节点时,根节点为null,指针不指向newN地址。当我找到一个为null的节点时,我想让他指向一个newN(一个info == x的节点以及左,右子项为null)。如何解决此问题?
public class Node {
public int info;
public Node left;
public Node right;
Node(int info) {
this.info = info;
}
}
public class BTree {
public Node root;
BTree() {
root = null;
}
public void add(int x) {
insert(root, x);
}
public boolean insert(Node r, int x) {
if (r == null) {
r = new Node(x);
return true;
}
else{
if (r.info == x) {
System.out.println("the value has already been added");
return false;
}
if (r.info < x)
insert(r.left, x);
if (r.info > x)
insert(r.right, x);
}
return false;
}
public void inOrder() {
inOrderTraverse(root);
}
public void inOrderTraverse(Node r) {
if (r != null) {
inOrderTraverse(r.left);
System.out.print(r.info + " ");
inOrderTraverse(r.right);
}
}
}
public class Main {
public static void main(String args[]){
BTree bt=new BTree();
bt.add(10);
bt.add(5);
bt.add(3);
bt.add(2);
bt.inOrder();
}
}
PS:我知道Java中没有指针,并且所有函数调用都是通过地址而不是值进行的.insert(Node r,int x)是否与c ++中的insert(Node&r,int&r)等效?
基本上,没有insert(Node r, int x)
不等同于insert(Node &r, int &x)
。 Java通过值而不是通过引用传递参数 。 更重要的是:
public boolean insert(Node r, int x) {
if (r == null) {
r = new Node(x);
return true;
}
else{
if (r.info == x) {
System.out.println("the value has already been added");
return false;
}
if (r.info < x)
insert(r.left, x);
if (r.info > x)
insert(r.right, x);
}
return false;
}
您假设为r
( new Node(x)
)赋值将为r
指向的位置赋值,但这不是Java理解事物的方式。 值分配给r
将覆盖的值r
即, r
现指新的Node
,但只有r
作为定位于insert()
函数。 所以r
不再与传入的原始值有任何联系。
您可以更简单地正确实现一些东西:
public void add(int x) {
if (this.root == null) {
this.root = new Node(x);
} else {
r = this.root;
if (x > r.info) {
while (r != null && x > r.info) {
r = r.right;
}
r.right = new Node(x);
}
// similarly for x < root.info, etc.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.