英文:
Building a Binary Search Tree in java. Unable to identify the reason for null error?
问题
创建节点
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left = null;
right = null;
}
}
创建树
//创建树
class Tree{
Node root = null;
void insert(Node temp, int data){
Node NewNode = new Node(data);
if(temp == null){
temp = NewNode;
}
else{
if(data < temp.data){
insert(temp.left, data);
}
else{
insert(temp.right, data);
}
}
}
}
主函数
public class test{
public static void main(String[] args) {
Tree t = new Tree();
t.insert(t.root, 3);
// t.insert(t.root,1);
System.out.println(t.root.data);
}
}
> 运行后我得到 t.root 为 null。我不明白为什么。需要一些帮助。
> 我将 t.root 传递为 temp,所以当 temp 被修改时,
> 这不意味着 t.root 也被修改了吗?
英文:
Creating the node
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left = null;
right = null;
}
}
Creating the tree
//create tree
class Tree{
Node root = null;
void insert(Node temp, int data){
Node NewNode = new Node(data);
if(temp == null){
temp = NewNode;
}
else{
if(data<temp.data){
insert(temp.left,data);
}
else{
insert(temp.right,data);
}
}
}
}
Main function
public class test{
public static void main(String[] args) {
Tree t = new Tree();
t.insert(t.root,3);
// t.insert(t.root,1);
System.out.println(t.root.data);
}
}
> Upon running I get t.root is null. I don't understand why. Need some
> help.
> I am passing t.root as temp, so when temp gets modified
> doesn't that mean t.root does too?
专注分享java语言的经验与见解,让所有开发者获益!
评论