将元素添加到树中
当我尝试向树添加一些元素时,我使用以下方法:
void add(City added, City parent){
//parentNode is where the element should be added
TreeNode<City> parentNode = search(parent,this);
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));
}
}
然而,问题是当我用“this”调用该方法时,我猜主树不会改变。例如,当树由一个元素组成时,我可以正确添加我想要的任何元素。但是,假设我的树由整数 1 组成,请忘记其他内容。当我向树中添加 2 个时,没有问题。但是当我想将 3 添加为 2 的孩子时,我的代码很糟糕!
我应该使用root吗?如果是的话,我应该如何实现它?
When I try to add some elements to a tree, I use the following method:
void add(City added, City parent){
//parentNode is where the element should be added
TreeNode<City> parentNode = search(parent,this);
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));
}
}
Yet, the problem is the that when I call the method with "this", I guess the main tree does not change. For instance, when the tree consists of one element, I am able to add any element I want correctly. However, say my tree consists of integer 1, forget about the other stuff. When I add 2 to my tree, no problem. But when I want to add 3 as the child of 2, my code sucks!
Should I use a root and if so, how should I implement it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论