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