-
-
Save unilecs/ffc6f85e7598c52691390bad2afe70bf to your computer and use it in GitHub Desktop.
Задача: Равенство бинарных деревьев
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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