在Python中,我可以将二叉树结构转换为任意嵌套列表:

    great
   /     \
  gr     eat
 / \    /   \
g   r  e    at
           /  \
          a    t

[great, [gr, [g, r], eat, [e, at, [a, t]]]


有没有一种方法可以在C#中构建一个任意的嵌套列表?

编辑:我从MSDN docsBinaryTree<T>类作为我的自定义StrBinaryTree类的基类。方法FormTree正在根据字符串创建树结构:

   public class StrBinaryTree : BinaryTree<string>
{
    public StrBinaryTree(string data)
    {
        if (data.Length == 0)
        {
            base.Root = null;
            base.Count = 0;
        }
        else
        {
            base.Root = new BinaryTreeNode<string>();
            base.Root.Data = data;
            base.Count = 1;
        }
    }

    public void FormTree(BinaryTreeNode<string> node)
    {
        var subLength = node.Data.Length / 2;
        if (subLength == 0)
            return;

        node.Left = new BinaryTreeNode<string>(node.Data.Substring(0, subLength));
        node.Right = new BinaryTreeNode<string>(node.Data.Substring(subLength));
        base.Count += 2;

        FormTree(node.Left);
        FormTree(node.Right);
    }
...}

最佳答案

尝试this solution

public static List<object> Solve(string input, List<object> list = null)
{
    if (list == null)
        return Solve(input, new List<object> { input });

    if (input.Length > 1)
    {
        var middle = input.Length / 2;
        var first = input.Substring(0, middle);
        var second = input.Substring(middle);

        var innerList = new List<object>();
        list.Add(innerList);

        foreach (var side in new[] { first, second })
        {
            innerList.Add(side);
            Solve(side, innerList);
        }
    }

    return list;
}

public static void Show(object input)
{
    if (!(input is string))
    {
        Console.Write("[");
        var list = input as List<object>;
        foreach (var item in list)
        {
            Show(item);
            if (item != list.Last())
                Console.Write(", ");
        }
        Console.Write("]");
    }
    else
        Console.Write(input);
}


用法:

var result = Solve("great");
Show(result);//[great, [gr, [g, r], eat, [e, at, [a, t]]]]


BinaryTreeNode的近似代码:

public static BinaryTreeNode<string> Solve(BinaryTreeNode<string> node)
{
    if(node.Data.Length > 1)
    {
        var middle = node.Data.Length / 2;
        var left = node.Data.Substring(0, middle);
        var right = node.Data.Substring(middle);

        node.Left = Solve(new BinaryTreeNode<string>(left));
        node.Right = Solve(new BinaryTreeNode<string>(right));
    }

    return node;
}


用法:

var result = Solve(new BinaryTreeNode<string>("great"));

关于c# - C#任意嵌套列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51530538/

10-15 19:41