C#能实现这种情况吗
本帖最后由 fangmin723 于 2018-1-20 12:31 编辑{{{1,2},{3,4},{5,6}} ,{{1,2},{3,4},{5 ,6}},{{1,2},{3,4},{5,6}}}
三维数组?List<二维数组>? List<List<List<>>>? sieben 发表于 2018-1-22 09:10
三维数组?List? List?
三维数组需要确定长度,我这长度不固定,List<二维数组>和 List<List<List<>>>都试过了,都达不到想要的效果 1、自己实现一个Tree
可以参考我的ResultTree类
2、你的问题实在不清晰,描述要准确 还是贴上一个简化的版本吧
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NFox.Collections
{
/// <summary>
/// 深度优先遍历模式
/// </summary>
public enum DepthSearchModeType
{
/// <summary>
/// 前序遍历
/// </summary>
Preorder,
/// <summary>
/// 中序遍历
/// </summary>
//Inorder,
/// <summary>
/// 后序遍历
/// </summary>
Postorder
}
public class Tree<T> : List<Tree<T>>
{
public T Value { get; set; }
public Tree<T> Parent
{ private set; get; }
public bool IsRoot
{
get { return Parent == null; }
}
public bool IsLeaf
{
get { return Count == 0; }
}
public Tree<T> Root
{
get
{
var node = this;
while (node.Parent != null)
{
node = node.Parent;
}
return node;
}
}
public Tree(){ }
public Tree(T value)
{
Value = value;
}
public bool IsAncestorOf(Tree<T> other)
{
Tree<T> node = other;
while (node.Parent != null)
{
node = node.Parent;
if (this == node)
return true;
}
return false;
}
public bool IsChildOf(Tree<T> other)
{
return other.IsAncestorOf(this);
}
public List<Tree<T>> Path
{
get
{
List<Tree<T>> lst = new List<Tree<T>> { this };
Tree<T> node = this;
while (node.Parent != null)
{
node = node.Parent;
lst.Insert(0, node);
}
return lst;
}
}
public int Depth
{
get { return Path.Count - 1; }
}
public new void Insert(int index, Tree<T> node)
{
node.Parent = this;
base.Insert(index, node);
}
public void InsertBefore(Tree<T> node, T value)
{
Insert(IndexOf(node), new Tree<T>(value));
}
public void InsertAfter(Tree<T> node, T value)
{
Insert(IndexOf(node) + 1, new Tree<T>(value));
}
public new void Add(Tree<T> node)
{
node.Parent = this;
base.Add(node);
}
public void Add(T value)
{
Add(new Tree<T>(value));
}
public new void AddRange(IEnumerable<Tree<T>> collection)
{
foreach (var tree in collection)
tree.Parent = this;
base.AddRange(collection);
}
public void AddRange(IEnumerable<T> collection)
{
AddRange(collection.Select(value => new Tree<T>(value)));
}
public void RemoveAll(Predicate<T> match)
{
base.RemoveAll(tree => match(tree.Value));
}
//深度优先
public void SearchByDepthFirst(DepthSearchModeType mode, Action<T> action)
{
if (mode == DepthSearchModeType.Preorder)
action(this.Value);
foreach (Tree<T> node in this)
node.SearchByDepthFirst(mode, action);
if (mode == DepthSearchModeType.Postorder)
action(this.Value);
}
//广度优先
public void SearchByBreadthFirst(Action<T> action)
{
Queue<Tree<T>> q = new Queue<Tree<T>>();
q.Enqueue(this);
while (q.Count > 0)
{
Tree<T> node = q.Dequeue();
action(node.Value);
node.ForEach(child => q.Enqueue(child));
}
}
}
}
页:
[1]