如果我有一棵这样的树:
A
B
C
D
E
F
如果用户搜索 C
,我想递归地向下钻取树,在 C
上设置一个属性(为此称为 Expanded
example) to true... 但随后也在其父项上设置该属性,因此 A
、B
和 C
将具有 Expanded
设置为 true。
我如何用递归完成这样的事情?
我有一个解决方案(抽象地)用于在树中最深的子级上设置属性,但是当展开回来时我在尝试为其每个父级设置该属性时遇到问题。
最佳答案
我的代码假定每个 Node
都有一个子 Nodes
集合。
第一步是检查当前 Node
是否匹配(在本例中为 value
)。如果是,则设置 Expanded
属性并将 true
返回给调用者。
否则,迭代子节点并递归调用DoSearch
。如果任何子节点匹配,则将 Expanded
属性设置为当前 Node
并将 true
返回给调用者。
bool DoSearch(Node n, int value)
{
if (n.Value == value)
{
n.Expanded = true;
return true; // let the caller know that the value was found
}
foreach (Node child in n.Nodes)
{
if (DoSearch(child, value)) // a child contains the value
{
n.Expanded = true;
return true; // let the caller know that the value was found
}
}
return false; // not found
}
关于javascript - 递归搜索父->子关系,将 bool 应用于分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43855038/