【问题标题】:Find Treeview node recursively递归查找Treeview节点
【发布时间】:2014-04-15 18:37:55
【问题描述】:

我有以下树

A
+-B
+-C 
| +-D
+-E
  +-F
  +-G

我正在尝试在给定A 的情况下找到G

private TreeListNode FindTreeNode(TreeListNode node, Enumerations.ItemType type,
                                  Nullable<long> id)
{
    TreeListNode found = null;
    foreach (TreeListNode child in node.Nodes)
    {
        if ((Enumerations.ItemType)child[2] == type)
        {
            if (id == null)
            {
                found = child;
                break;
            }
            else
            {
                if ((long)child[0] == (long)id)
                {
                    found = child;
                    break;
                }
            }
        }
        else
        {
            if (child.HasChildren)
            {
                found = FindTreeNode(child, type, id);
                break;
            }
        }
    }
    return found;
}
FindTreeNode(root,C,null)

由于C 出现在G 之前,因此该例程可用于查找C 及其子项。 如果 else 块 if(child.HasChildren) 它找到 C 和它的孩子。 当我试图找到E 及其孩子时, 递归调用无法正常工作。 它带有根节点A,但进入递归后,子节点变为C,然后变为nodes.Nodes = 1

当我搜索FG 时,它必须继续递归。那么如何将孩子设置为根节点

【问题讨论】:

  • TreeView search 的可能重复项
  • 您的TreeListNode 是什么样的?为什么你将C 作为第二个参数传递给FindTreeNode?从签名来看,它应该是Enumerations.ItemType

标签: c#


【解决方案1】:

即使递归调用没有找到任何东西,你也会中断。将相关代码改为:

if (child.HasChildren)
{
    found = FindTreeNode(child, type, id);
    if (found != null) 
        break;
}

你的方法看起来很复杂。这不也一样吗?

private TreeListNode FindTreeNode(TreeListNode node, Enumerations.ItemType type,
                                  Nullable<long> id)
{
    foreach (TreeListNode child in node.Nodes) {
        if ((Enumerations.ItemType)child[2] == type &&
            (id == null || (long)child[0] == id.Value)) {

            return child;
        }

        if (child.HasChildren) {
            TreeListNode found = FindTreeNode(child, type, id);
            if (found != null) {
                return found;
            }
        }
    }
    return null;
}

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2011-10-02
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多