C# 为什么我的_根在这里停留在null?
我已经通过了密码C# 为什么我的_根在这里停留在null?,c#,.net,algorithm,binary-search-tree,C#,.net,Algorithm,Binary Search Tree,我已经通过了密码 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) { BinaryTr
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);
}
}
}
最初会被调用。街区
else
{
root = new Node() { val = newval, left = null, right = null };
}
应该将其设置为非空,但事实并非如此。。。除非我遗漏了什么
root
是Add
函数作用域中的局部变量。最初,root
和\u root
指向同一个对象,但通过为其分配一个新节点
,您只能更改root
指向的对象。它不会更改根目录所指向的内容
您需要直接设置
\u root
,或者将root
设置为参数。root
是Add
函数的局部变量。最初,root
和\u root
指向同一个对象,但通过为其分配一个新节点
,您只能更改root
指向的对象。它不会更改根目录所指向的内容
您需要直接设置
\u root
,或者使root
成为一个参数。我认为节点
是一个对象
,因此已经通过引用传递。对象是通过引用传递的,但对该对象的引用不是通过引用传递的。i、 e.如果在节点
上调用变异方法,则\u root
和root
都将反映该更改。另一方面,如果您只是将值赋给\u root
或root
,则另一个值不会反映该更改。我认为节点
是对象,因此已通过引用传递。对象是通过引用传递的,但对该对象的引用不是通过引用传递的。i、 e.如果在节点
上调用变异方法,则\u root
和root
都将反映该更改。另一方面,如果只为\u root
或root
分配一个值,则另一个值不会反映该更改。
else
{
root = new Node() { val = newval, left = null, right = null };
}