布尔递归
试图编写一个布尔方法来判断某人是否是某人的后代......但似乎无法做到这一点。当然,如果该对象是孩子……或者孩子的后代,那么它就是后代。
public boolean isDescendant(member x){
if (children.contains(x)){
return true;
}
else{
return false;
}
}
但我在哪里或如何插入:
for (int i = 0; i < children.size(); i++){
isDescendant(children.get(i));
}
谢谢!
trying to write a boolean method that tells if someone is a decendant of someone...but can't seem to do it. of course, the object is a descendant if it's a child...or the descendant of a child.
public boolean isDescendant(member x){
if (children.contains(x)){
return true;
}
else{
return false;
}
}
but where or how do i insert:
for (int i = 0; i < children.size(); i++){
isDescendant(children.get(i));
}
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想你想要的如下:
I think what you want is below:
树木向下行走的速度非常慢(从根部到叶子)。考虑 is-ancestor 检查的这种实现:
另一种方法现在是小菜一碟。
没有循环,没有指数级的努力。
PS:
在我的示例中,我建议将 isDescendant 重命名为 isAncestorOf。
Walking trees is very slow downwards (from the root to the leaves). Consider this implementation for the is-ancestor check:
The other way is now a piece of cake.
No loops, no exponentional effort.
PS:
In my example i would suggest renaming
isDescendant
toisAncestorOf
.您很可能需要递归当前的根。
You need to recurse over the current root, most likely.
编辑:如果您的数据结构有父指针,请使用这些指针而不是在树中搜索您的后代。如果没有,请考虑添加它们。请参阅威士忌塞拉 (whiskysierra) 的答案,了解带有父指针的解决方案。仅当无法添加它们时,才考虑这个答案。
当前的答案都有两个通过子项的循环(一个在
children.contains()
中,一个在后面)。这个变体可能更高效一些(但它不会改变 O 级),并且更短一些。 (如果children是一个具有快速包含检查的集合(如HashSet),并且层次结构通常不是那么深(因此您根本不需要递归),那么其他答案更好。)
如果一个节点被认为是后代就其本身而言,你可以这样写:
Edit: If your data structure has parent pointers, use these instead of searching your descendants in the tree. If not, consider adding them. See the answer from whiskeysierra for a solution with parent pointers. Only if adding them is not possible, consider this answer.
The current answers all have two loops through children (one in
children.contains()
, one later).This variant may be a bit more efficient (but it does not change the O-class), and is a bit shorter. (If children is a set with fast contains-check (like HashSet) and often the hierarchy is not so deep (so you don't need to recurse at all), the other answers are better.)
If a node is considered a descendant of itself, you can write it like this: