Set Deepth for each node in forest
3607 ワード
Set Deepth for each tree node of a forest TreeNode Entity:
SetTreeDeepth:
Test Method:
public class TreeNode
{
public string Name { get; set; }
public TreeNode ParrentNode { get; set; }
public List<TreeNode> LstChildren { get; set; }
public int Deep { get; set; }
public void AddChildren(TreeNode node)
{
LstChildren.Add(node);
node.ParrentNode = this;
}
}
SetTreeDeepth:
#region tree
public void SetTreeDeep(TreeNode current)
{
current.Deep = GetDeepth(current);
if (!current.LstChildren.Any())
return;
foreach (var children in current.LstChildren)
{
SetTreeDeep(children);
}
}
public int GetDeepth(TreeNode node)
{
if (node == null)
return 0;
if (node.LstChildren.Any())
{
var deepArr = node.LstChildren.Select(GetDeepth).ToList();
var maxChildDeep = deepArr.Max() + 1;
return maxChildDeep;
}
return 0;
}
#endregion
Test Method:
[TestMethod]
public void SetTreeDeep()
{
// root
// / | \
// t1 t2 t3
// / \ / \
// t4 t5 t6 t7
// / \ \
// 8 9 t10
var nodeLst = new List<TreeNode>
{
new TreeNode() {Name = "Root", LstChildren = new List<TreeNode>(), Deep = 0, ParrentNode = null},
new TreeNode() { Name = "T1", LstChildren = new List<TreeNode>(), Deep = 0 },
new TreeNode() { Name = "T2", LstChildren = new List<TreeNode>(), Deep = 0 },
new TreeNode() { Name = "T3", LstChildren = new List<TreeNode>(), Deep = 0 },
new TreeNode() { Name = "T4", LstChildren = new List<TreeNode>(), Deep = 0 },
new TreeNode() { Name = "T5", LstChildren = new List<TreeNode>(), Deep = 0 },
new TreeNode() { Name = "T6", LstChildren = new List<TreeNode>(), Deep = 0 },
new TreeNode() { Name = "T7", LstChildren = new List<TreeNode>(), Deep = 0 },
new TreeNode() { Name = "T8", LstChildren = new List<TreeNode>(), Deep = 0 },
new TreeNode() { Name = "T9", LstChildren = new List<TreeNode>(), Deep = 0 },
new TreeNode() { Name = "T10", LstChildren = new List<TreeNode>(), Deep = 0 }
};
nodeLst[7].AddChildren(nodeLst[10]);
nodeLst[3].AddChildren(nodeLst[6]);
nodeLst[3].AddChildren(nodeLst[7]);
nodeLst[0].AddChildren(nodeLst[3]);
nodeLst[0].AddChildren(nodeLst[2]);
nodeLst[5].AddChildren(nodeLst[8]);
nodeLst[5].AddChildren(nodeLst[9]);
nodeLst[1].AddChildren(nodeLst[4]);
nodeLst[1].AddChildren(nodeLst[5]);
nodeLst[0].AddChildren(nodeLst[1]);
var stds = new SetTreeDeepSample();
stds.SetTreeDeep(nodeLst[0]);
var ret = String.Join(",", nodeLst.Select(n => n.Deep).ToArray());
//expected result :3,2,0,2,0,1,0,1,0,0,0
}