javascript - 递归搜索父->子关系,将 bool 应用于分支

标签 javascript c# algorithm recursion

如果我有一棵这样的树:

A
  B
    C
D
  E
F

如果用户搜索 C,我想递归地向下钻取树,在 C 上设置一个属性(为此称为 Expanded example) to true... 但随后也在其父项上设置该属性,因此 ABC 将具有 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/

相关文章:

javascript - 过滤掉未定义的属性

javascript - 如何重构二进制递归以使其与蹦床功能兼容?

c# - 匿名委托(delegate) - 使用对象集合搜索属性

c# - 创建 Excel 2007 工作簿的最佳做法是什么

c# - 在 web api Controller (.net 核心)中使用异步/等待或任务

c# - 购物车中的特殊逻辑\算法

javascript - 怎么才能达到 "lava"留下痕迹的效果

c - 从电话数字键盘按字母顺序搜索

javascript - 如何填充和规范化可变长度数组

javascript - 在 Localhost 上测试 Google Analytics