【问题标题】:Why is my _root here stuck at null?为什么我的 _root 卡在这里?
【发布时间】:2016-06-05 01:43:15
【问题描述】:

我已经浏览了

的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericBinaryTree
{
    class Program
    {
        static void Main(string[] args)
        {
            BinaryTree<int> B = new BinaryTree<int>();
            Random rnd = new Random();
            for(int i = 0; i <= 100; ++i)
            {
                B.Add(rnd.Next(Int32.MinValue, Int32.MaxValue));
            }
            B.Print();
        }
    }

    class BinaryTree<T> where T : IComparable<T>
    {
        public class Node
        {
            public T val { get; set; }
            public Node left { get; set; }
            public Node right { get; set; }
        }

        private Node _root = null;

        public void Add ( T newval )
        {
            Add(newval, _root);
        }

        private void Add ( T newval, Node root )
        {
            if(root != null)
            {
                if(newval.CompareTo(root.val) < 0)
                    Add(newval, root.left);
                else if(newval.CompareTo(root.val) > 0)
                    Add(newval, root.right);
            }
            else
            {
                root = new Node() { val = newval, left = null, right = null };
            }
        }

        public void Print ( )
        {
            if(_root != null)
                PrintValAndDescendants(_root);     
        }

        private void PrintValAndDescendants ( Node  n )
        {
            Console.WriteLine(n);
            if(n.right != null) PrintValAndDescendants(n.right);
            if(n.left != null) PrintValAndDescendants(n.left);
        }
    }
}

我不明白为什么我的_root 没有设置好

Add(newval, _root);

最初被调用。块

else
{
   root = new Node() { val = newval, left = null, right = null };
}

应该使它成为非null,但事实并非如此......除非我缺少某些东西。

【问题讨论】:

    标签: c# .net algorithm binary-search-tree


    【解决方案1】:

    rootAdd 函数范围内的局部变量。最初,root_root 指向同一个对象,但通过为其分配 new Node,您只会更改 root 指向的对象。它不会改变_root 指向的内容。

    您需要直接设置_root,或将root 设为ref 参数。

    【讨论】:

    • 我认为NodeObject,因此已经通过引用传递。
    • 对象是通过引用传递的,但对该对象的引用不是通过引用传递的。即,如果您在 Node 上调用变异方法,_rootroot 都将反映该更改。另一方面,如果您只是为_rootroot 分配一个值,则另一个不会反映该更改。
    猜你喜欢
    • 2018-10-29
    • 2010-12-25
    • 1970-01-01
    • 2020-07-31
    • 2021-11-08
    • 2019-09-09
    • 2020-11-14
    • 2016-11-22
    • 2015-10-25
    相关资源
    最近更新 更多