【发布时间】:2017-06-20 13:59:07
【问题描述】:
我的方法看起来像
static Node _root = null;
static void AddToTree(int val)
{
AddToTree(val, ref _root);
}
static void AddToTree(int val, ref Node root)
{
if(root == null)
root = new Node() { Val = val };
Node left = root.Left, right = root.Right;
if(root.Val > val)
AddToTree(val, ref left);
else if(root.Val < val)
AddToTree(val, ref right);
}
我如何看到它失败是我运行
int[] vals = { 2, 1, 5, 3, 8 };
foreach(int i in vals)
AddToTree(i);
Print();
哪个使用
static void Print()
{
if(_root == null)
return;
LinkedList<int> vals = new LinkedList<int>();
Queue<Node> q = new Queue<Node>();
q.Enqueue(_root);
while(q.Count > 0)
{
Node front = q.Dequeue();
vals.AddLast(front.Val);
if(front.Right != null)
q.Enqueue(front.Right);
if(front.Left != null)
q.Enqueue(front.Left);
}
Console.WriteLine(string.Join(",", vals));
}
我看到的输出是
2
即添加的第一个元素,没有其他元素。
知道我哪里出错了吗?
【问题讨论】:
-
您是否尝试通过放置断点并单步执行来调试您的代码?
标签: c# algorithm data-structures