The method of adding a new node does not work.

class BinaryTree { class BinaryNode //узел дерева { public BinaryTree left { get; set; } //указатели узла public BinaryTree right { get; set; } public int value; //вставляемое значение public BinaryNode(int val) { value = val; //конструктор заполняет узел значением left = null; right = null; } } class Tree //создание дерева { public BinaryNode root; //корень дерева public Tree() //конструктор (по умолчанию) создания дерева { root = null; //при создании корень не определен } public Tree(int value) { root = new BinaryNode(value); //если изначально задаём корневое значение } //нерекурсивное добавление public void Add(int value) //узел и его значение { if (root == null) //если корня нет { root = new BinaryNode(value); //добавляем элемент как корневой return; } BinaryNode current = root; //текущий равен корневому bool added = false; //обходим дерево do { if (value >= current.value) //идём вправо { if (current.right == null) { current.right = new BinaryNode(value); added = true; } else { current = current.right; } } if (value<current.value) //идём влево { if(current.left == null) { current.left = new BinaryNode(value); added = true; } else { current = current.left; } } else { current = current.left; } } while (!added); } 

The right side is highlighted in red (for the right and left subtree).

 current.right = new BinaryNode(value); current = current.right; 

What could be wrong here?

    1 answer 1

    Well, it should not compile, because you have current.right - this is BinaryTree , and you assign it to BinaryNode . Your BinaryTree conceived, apparently, as a facade for the implementation of the entire tree, so your left and right should be BinaryNode .

    Then, it is not clear why you need an empty BinaryTree class. Perhaps you should “merge” together the Tree and BinaryTree . It turns out this:

     public class BinaryTree //создание дерева { public class BinaryNode //узел дерева { public BinaryNode left { get; set; } //указатели узла public BinaryNode right { get; set; } public int value; //вставляемое значение public BinaryNode(int val) { value = val; //конструктор заполняет узел значением left = null; right = null; } } public BinaryNode root; //корень дерева public BinaryTree() //конструктор (по умолчанию) создания дерева { root = null; //при создании корень не определен } public BinaryTree(int value) { root = new BinaryNode(value); //если изначально задаём корневое значение } //нерекурсивное добавление public void Add(int value) //узел и его значение { 

    etc.

    I have it compiled, but I did not check the correctness of the code.