[英]Binary tree in C#
我正在尝试建立一个二叉树,但是由于某种原因,我的代码无法正常工作。 有人能帮帮我吗? 我输入随机数,然后...我无法真正解释它,最好自己运行并在调试中查看结果;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
leaf root = new leaf();
while (true)
{
string read = Console.ReadLine();
if (read == "print")
{
root.print();
}
else
{
root.grow(Convert.ToInt32(Console.ReadLine()));
}
}
}
}
class leaf
{
public void print()
{
}
public void grow(int value)
{
if (isNull)
{
isNull = false;
this.value = value;
smaller = bigger = new leaf();
}
else
{
if (value > this.value)
{
bigger.grow(value);
}
else
{
smaller.grow(value);
}
}
}
public bool isNull = true;
public int value;
leaf smaller;
leaf bigger;
}
}
问题:对于输入:1 2 3 4 13 6 4 7 8
它生成以下树(跳过数字,我不知道为什么):
2
/ \
4
/ \
6
/ \
7
/ \
我怀疑这是您的问题:
smaller = bigger = new leaf();
您已经创建了一个对象,并为smaller
和bigger
分配了对该对象的引用。 因此主叫smaller.grow()
等效于调用bigger.grow()
尝试这个:
smaller = new leaf();
bigger = new leaf();
(作为一个旁注,我强烈建议您开始遵循.NET命名约定,以使您的代码更易于其他开发人员阅读,并且与其他代码更加一致。)
我的猜测是,如果您准确地写出您正在做的事情,答案将会更加清楚。
您输入的内容是:1 2 3 4 13 6 4 7 8,但这将不会导致任何结果:
string read = Console.ReadLine();
会消耗掉它并循环到同一行等待输入。 我的猜测是您的实际输入是:
1个
2
3
13
6
4
7
8
但将以上各行消耗掉其他所有行,则仅2,4,6,7会被该行消耗:
root.grow(Convert.ToInt32(Console.ReadLine()));
与您的结果相对应。 将最后一行(在做出乔恩建议的更改后)更改为:
root.grow(Convert.ToInt32(read));
可以解决问题(如果我对您实际输入的假设是正确的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.