gpt4 book ai didi

java - 在java树中查找子节点(递归)

转载 作者:行者123 更新时间:2023-12-02 03:36:19 26 4
gpt4 key购买 nike

感谢您查看。我想要的是获取树,其中 root id 是 param 传递的 id,但返回空指针。

树设置

TreeIF<DoctorIF> tree = new Tree<DoctorIF>();

setTree(tree);

DoctorS ceo = new DoctorS(1, this);
DoctorS two = new DoctorS(2, this);
DoctorS three = new DoctorS(3, this);
DoctorS four = new DoctorS(4, this);
DoctorS five = new DoctorS(5, this);
DoctorS six = new DoctorS(6, this);
DoctorS seven = new DoctorS(7, this);

TreeIF<DoctorIF> t1 = new Tree<DoctorIF>(three);
TreeIF<DoctorIF> t2 = new Tree<DoctorIF>(four);
TreeIF<DoctorIF> t3 = new Tree<DoctorIF>(two);
tree.setRoot(ceo);

t1.addChild(new Tree<DoctorIF>(seven));
t2.addChild(new Tree<DoctorIF>(five));
t3.addChild(t1);
t3.addChild(t2);
t3.addChild(new Tree<DoctorIF>(six));

tree.addChild(t3);

获取树或树子节点的函数。当我搜索 id {4,5,6,7} 时,我得到了空指针。

private TreeIF<DoctorIF> getTreeChild(TreeIF<DoctorIF> tree_, int id){
if (tree_.getRoot().getId()==id && id!=1)return tree_;
else{
ListIF<TreeIF<DoctorIF>> list = tree_.getChildren();
IteratorIF<TreeIF<DoctorIF>> it = list.getIterator();
while(it.hasNext()){
TreeIF<DoctorIF> subtree = getTreeChild(it.getNext(), id);
if (subtree.getRoot()!=null && subtree.getRoot().getId()==id)return subtree;
}
}
return null;
}

@Override
public DoctorIF getDoctor(int id){
TreeIF<DoctorIF> tree_ = null;
tree_ = getTreeChild(tree, id);
return tree_.getRoot();
}

最佳答案

我添加了一些评论来解释我的更改:

private TreeIF<DoctorIF> getTreeChild(TreeIF<DoctorIF> tree_, int id){
if (tree_.getRoot().getId()==id && id!=1)return tree_;
else{
ListIF<TreeIF<DoctorIF>> list = tree_.getChildren();
IteratorIF<TreeIF<DoctorIF>> it = list.getIterator();
while(it.hasNext()){
TreeIF<DoctorIF> subtree = getTreeChild(it.getNext(), id);
//subtree might be null at this point
//In that case, subtree.getRoot() will throw a NullPointerException
if (subtree == null) continue; //This will prevent the NullPointerException
if (subtree.getRoot()!=null && subtree.getRoot().getId()==id)return subtree;
}
}
return null;
}

关于java - 在java树中查找子节点(递归),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37415108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com