【问题标题】:How to write GetEnumerator() for a Binary Search Tree?如何为二叉搜索树编写 GetEnumerator()?
【发布时间】:2014-12-12 10:25:01
【问题描述】:

我有一个BinaryTree 类和一个用于保存节点的BinaryTreeNode,我已经制作了树并为其编写了 pre-order、postorder 和 in-order 方法。
但我不知道如何为它写IEnumerator<T>(我只想对GetEnumerator() 方法使用in-order)。 问题是inOrder 方法的返回类型是void。我想让它IEnumerator<T> 而不是MessageBox 返回数据。

我该怎么做?

public void PreOrder(BinaryTreeNode<T> node)
{
    if (node != null)
    {
        MessageBox.Show(node.Value.ToString());
        PreOrder(node.Left);
        PreOrder(node.Right);
    }
}

public void PostOrder(BinaryTreeNode<T> node)
{
    if (node != null)
    {
        PostOrder(node.Left);
        PostOrder(node.Right);
        MessageBox.Show(node.Value.ToString());
    }
}

public void InOrder(BinaryTreeNode<T> node)
{
    if (node != null)
    {
        InOrder(node.Left);
        MessageBox.Show(node.Value.ToString());
        InOrder(node.Right);
    }
}

public void Clear()
{
    root = null;
    Count = 0;
}

public IEnumerator<T> GetEnumerator()
{
    InOrder(root);
    return null; // error in forerach loop
}

IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

我认为我的这部分代码已经足够了。
这就是我定义BinaryTree 类的方式:

public class BinaryTree<T> : IEnumerable<T> where T : IComparable<T>

这就是我定义BinaryTreeNode的方式:

public class BinaryTreeNode<T> : IComparable<T> where T : IComparable<T>

【问题讨论】:

    标签: c# algorithm generics data-structures binary-search-tree


    【解决方案1】:

    这是一种方法,使用yield

    public IEnumerator<T> GetEnumerator()
    {
        if (Left != null)
        {
            foreach(var v in Left)
            {
                yield return v;
            }
        }
    
        yield return Value;
    
        if (Right != null) 
        {
            foreach (var v in Right)
            {
                yield return v;
            }
        }
    }
    

    这是使用 Linq 的更简洁的方法:

    public IEnumerator<T> GetEnumerator()
    {
        var leftEnumerable = (IEnumerable<T>)Left ?? new T[0];
        var rightEnumerable = (IEnumerable<T>)Right ?? new T[0];
    
        return leftEnumerable.Concat(new T[] { Value })
                             .Concat(rightEnumerable)
                             .GetEnumerator();
    }
    

    编辑:由于您似乎对BinaryTreeBinaryTreeNode 有单独的类,您可以将上述任何一个放入BinaryTreeNode,并将以下放入BinaryTree

    public IEnumerator<T> GetEnumerator()
    {
        return Root.GetEnumerator();
    }
    

    【讨论】:

    • 我在 BinaryTree 中没有 Left 属性。它在 BinaryTreeNode 中。并且 GetEnumerator() 在 BinaryTree 中。所以左,右在这里不起作用。您想查看完整的代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2019-03-09
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2010-10-26
    相关资源
    最近更新 更多