我有一些课。
class TreeNode
{
public TreeNode Left;
public TreeNode Right;
public int Value;
public TreeNode(int i)
{
Value = i;
}
public TreeNode AddLeft(int value)
{
Left = new TreeNode(value); ;
return Left;
}
public TreeNode AddRight(int value)
{
Right = new TreeNode(value);
return Right;
}
public static int GetSum(TreeNode root)
{
if(root.Left == null || root.Right == null) return root.Value;
return root.Value + GetSum(root.Left) + GetSum(root.Right);
}
}
class Program
{
static void Main(string[] args)
{
var root = new TreeNode(10);
var left = root.AddLeft(1);
left.AddLeft(1);
left.AddRight(1);
var right = root.AddRight(1);
right.AddLeft(1);
right.AddRight(1);
int Sum = TreeNode.GetSum(root);
Console.WriteLine("Sum is :{0}", Sum);
Console.ReadKey();
}
}
如何简化树初始化,因为如果树很大,很容易混淆?
答案 0 :(得分:6)
类似的东西:
var root = new TreeNode(10,
new TreeNode(1,
new TreeNode(1),
new TreeNode(1)),
new TreeNode(1,
new TreeNode(1),
new TreeNode(1)));
看起来更干净,您怎么看?您需要做的就是添加一个新的构造函数:
public TreeNode(int value, TreeNode left, TreeNode right)
{
Value = value;
Left = left;
Right = right;
}
答案 1 :(得分:5)
除了Daren Thomas's answer之外,如果您希望初始化更具可读性,您可以使用C#4.0的named parameter功能
var root = new TreeNode(10,
left: new TreeNode(1,
left: new TreeNode(1),
right: new TreeNode(1)),
right: new TreeNode(1,
left: new TreeNode(1),
right: new TreeNode(1)));
答案 2 :(得分:1)
为树创建XML表示或JSON表示,您也可以加载或保存。
答案 3 :(得分:1)
C#对象初始值设定项可以提供更简洁的代码,以及为什么需要额外的构造函数来支持该语言支持的内容。
public class TreeNode
{
public TreeNode Left { get; set; }
public TreeNode Right { get; set; }
}
static void Main(string[] args)
{
var root = new TreeNode { Left = new TreeNode {Left = new TreeNode() },
Right = new TreeNode() };
}