Подсчет узлов содержащих два поддерева в бинарном дереве - C#
Формулировка задачи:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Tree t = new Tree();
int c = 0;
t.Insert(8);
t.Insert(6);
t.Insert(10);
t.Insert(12);
t.Insert(45);
t.Insert(3);
t.Insert(4);
t.Insert(2);
t.Insert(1);
t.Insert(0);
Console.WriteLine(t.Display());
Console.WriteLine(t.Count(c));
Console.ReadKey();
}
}
class Tree
{
private int value;
private Tree left;
private Tree right;
public Tree()
{
this.value = 0;
}
public void Insert(int value)
{
if (this.value == 0)
this.value = value;
else
{
if (this.value < value)
{
if (left == null)
this.left = new Tree();
left.Insert(value);
}
else if (this.value > value)
{
if (right == null)
this.right = new Tree();
right.Insert(value);
}
else
throw new Exception("Узел уже существует");
}
}
public string Display()
{
string result = "";
if (this.left != null)
result += this.left.Display();
result += this.value + " ";
if (this.right != null)
result += this.right.Display();
return result;
}
public int Count(int c)
{
if ((left != null) && (right != null)) c++;
if (this.left!= null) this.left.Count(c);
if (this.right!= null) this.right.Count(c);
return c;
}
}
}Решение задачи: «Подсчет узлов содержащих два поддерева в бинарном дереве»
textual
Листинг программы
public int Count(ref int c)
{
if ((left != null) && (right != null)) c++;
if (this.left!= null) this.left.Count(ref c);
if (this.right!= null) this.right.Count(ref c);
return c;
}