Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created March 21, 2019 06:08
Show Gist options
  • Save unilecs/ffc6f85e7598c52691390bad2afe70bf to your computer and use it in GitHub Desktop.
Save unilecs/ffc6f85e7598c52691390bad2afe70bf to your computer and use it in GitHub Desktop.
Задача: Равенство бинарных деревьев
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("UniLecs");
var treeA = new Node(10)
{
Left = new Node(5)
{
Right = new Node(2)
},
Right = new Node(20)
{
Left = new Node(25),
Right = new Node(35)
}
};
var treeB = new Node(10)
{
Left = new Node(5)
{
Left = new Node(2)
},
Right = new Node(20)
{
Left = new Node(25),
Right = new Node(35)
}
};
Console.WriteLine(string.Format("Answer = {0}", TreesAreIdentical(treeA, treeA))); // True
Console.WriteLine(string.Format("Answer = {0}", TreesAreIdentical(treeA, treeB))); // False
}
private static bool TreesAreIdentical(Node treeA, Node treeB)
{
// один из выходов рекурсии: если оба узла отстуствуют
if (treeA == null && treeB == null)
{
return true;
}
// если узлы существуют для обоих деревьев,
// то проверяем равенство их значений и проверяем левое и правое под-дерево
if (treeA != null && treeB != null)
{
return ((treeA.Value == treeB.Value) &&
TreesAreIdentical(treeA.Left, treeB.Left) &&
TreesAreIdentical(treeA.Right, treeB.Right));
}
// деревья не равны
return false;
}
}
public class Node
{
public int Value { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public Node(int Value)
{
this.Value = Value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment