C#中的二叉树

Gil*_*man 1 c# binary-tree

我正在尝试构建一个二叉树,但由于某种原因我的代码不起作用.有人能帮帮我吗?我输入随机数,它...我无法解释它,最好自己运行它并在调试中看到结果;

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题: 输入:1 2 3 4 13 6 4 7 8

它生成以下树(跳过数字,我不知道为什么):

   2
  / \
     4
    / \
       6
      / \
         7
        / \
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

这是你的问题,我怀疑:

smaller = bigger = new leaf();
Run Code Online (Sandbox Code Playgroud)

您已经创建了一个对象,并分配给两个对它的引用smallerbigger.因此,呼叫smaller.grow()等同于呼叫bigger.grow().

试试这个:

smaller = new leaf();
bigger = new leaf();
Run Code Online (Sandbox Code Playgroud)

(作为旁注,我强烈建议您开始遵循.NET命名约定,以便让其他开发人员更容易阅读代码,并且与其他代码更加一致.)