【问题标题】:Where is the flaw in my algorithm for adding a node to a binary tree?我将节点添加到二叉树的算法中的缺陷在哪里?
【发布时间】: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


【解决方案1】:

这个代码序列并没有像你想象的那样做:

Node left = root.Left;
Foo(ref left);

您通过引用传递left,而不是root.Left。现在当Foo() 重新分配left 时,只有left 会受到影响,root.Left 不会受到影响。

当然是can't pass properties by reference,所以解决方案是在Foo() 返回后重新分配root.Left = left

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多