void add(City added, City parent){
//added is what is going to be added and child of parent. I first find parent in tree
//search method is coming after
TreeNode<City> parentNode = search(parent,this);
if (parentNode.hasLeftChild() && parentNode.getLeftChild().getCity().equals(parent))
parentNode = parentNode.getLeftChild();
else if (parentNode.hasNextSibling() && parentNode.getNextSibling().getCity().equals(parent))
parentNode = parentNode.getNextSibling();
else if (!parentNode.hasLeftChild())
parentNode.setLeftChild(new TreeNode<City>(added,null,null));
else {
TreeNode<City> next = parentNode.getLeftChild();
while(next.hasNextSibling())
next = next.getNextSibling();
next.setNextSibling(new TreeNode<City>(added,null,null));
}
}
public TreeNode<City> search(City parent, TreeNode<City> t){
if (t.getCity().equals(parent))
return t;
else if (t.hasLeftChild())
return search(parent,t.getLeftChild());
else
return search(parent,t.getNextSibling());
}
我一直在服用nullpointerexception并且不知道该怎么做。任何人都有更好的想法来搜索元素并添加它。或者至少有一个网站让我学习那个狗屎???
答案 0 :(得分:0)
您必须测试树为空的基本情况,以便您尝试添加的节点将真正成为树的根。