gpt4 book ai didi

c# - C#中的二叉树

转载 作者:太空宇宙 更新时间:2023-11-03 17:45:53 24 4
gpt4 key购买 nike

我正在尝试建立一个二叉树,但是由于某种原因,我的代码无法正常工作。
有人能帮帮我吗?
我输入随机数,然后...
我不能真正解释它,最好是自己运行它并在调试中查看结果。

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
/ \

最佳答案

我的猜测是,如果您准确地写出您正在做的事情,答案将会更加清楚。

您输入的内容是: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));


可以解决问题(如果我对您实际输入的假设是正确的)

关于c# - C#中的二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4469075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com