在Java问题中将节点插入二叉树 [英] inserting nodes into a binary tree in java question
问题描述
我从C ++到Java,我对Java的二叉树感到困惑. Node类的唯一方法是使其成为内部静态类?我看到的所有示例都可以做到这一点.但是,即时通讯的方式是我有一个节点类,而binarytree类使用此节点类.但是当我尝试在第二次插入后插入树中时,我一直收到错误消息.我在此行if(dataIn <= nodeIn.getLeft().getData()){
im coming from c++ to java and i am confused on binary trees with java. is the only way to have a Node class is to make it an inner static class? all the examples i see do this. However, the way im doing it is i have a node class and a binarytree class uses this node class. but i keep getting an error when i try inserting into the tree after the second insert. i get an exception at this line if(dataIn <= nodeIn.getLeft().getData()){
我对我做错了感到困惑....这是我插入的代码.预先感谢..
I am confused as to what i did wrong.... here is my code for insert that i have. thanks in advance..
public void insert(int dataIn){
root = insert(root, dataIn);
}
private Node insert(Node nodeIn, int dataIn){
if(nodeIn==null){
nodeIn = new Node(null, null, dataIn);
}else{
if(dataIn <= nodeIn.getLeft().getData()){
nodeIn.setLeft(insert(nodeIn.getLeft(), dataIn));
}else{
nodeIn.setRight(insert(nodeIn.getRight(), dataIn));
}
}
return nodeIn;
}
推荐答案
您需要测试是否nodeIn.getLeft() == null
.
这篇关于在Java问题中将节点插入二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!