Created
November 16, 2017 12:19
-
-
Save AndreyBespamyatnov/db25681d90e496325009dd813e764b94 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
private static bool CompareIterative(BTN n1, BTN n2) | |
{ | |
// check for nulls | |
if (n1 == null || n2 == null) | |
{ | |
return n1 == n2; | |
} | |
var q1 = new Queue<BTN>(); | |
var q2 = new Queue<BTN>(); | |
q1.Enqueue(n1); | |
q2.Enqueue(n2); | |
while (q1.Count > 0 && q2.Count > 0) | |
{ | |
// get nodes and compare them | |
var tempNode1 = q1.Dequeue(); | |
var tempNode2 = q2.Dequeue(); | |
if (tempNode1.Val != tempNode2.Val) | |
{ | |
return false; | |
} | |
// enqueue Left children of both nodes | |
if (tempNode1.Left != null && tempNode2.Left != null) | |
{ | |
q1.Enqueue(tempNode1.Left); | |
q2.Enqueue(tempNode2.Left); | |
} | |
else if (tempNode1.Left == null && tempNode2.Left == null) | |
{ | |
// do nothing | |
} | |
else if (tempNode1.Left == null || tempNode2.Left == null) | |
{ | |
return false; | |
} | |
// enqueue Right children of both nodes | |
if (tempNode1.Right != null && tempNode2.Right != null) | |
{ | |
q1.Enqueue(tempNode1.Right); | |
q2.Enqueue(tempNode2.Right); | |
} | |
else if (tempNode1.Left == null && tempNode2.Left == null) | |
{ | |
// do nothing | |
} | |
else if (tempNode1.Right == null || tempNode2.Right == null) | |
{ | |
return false; | |
} | |
} | |
return true; | |
} | |
private static bool CompareRecursive(BTN n1, BTN n2) | |
{ | |
// check for nulls | |
if (n1 == null || n2 == null) | |
{ | |
return n1 == n2; | |
} | |
// check data of the root nodes | |
if (n1.Val != n2.Val) | |
{ | |
return false; | |
} | |
// check left sub trees recursively | |
var leftIsEquals = CompareRecursive(n1.Left, n2.Left); | |
// check right sub trees recursively | |
var rightIsEquals = CompareRecursive(n1.Right, n2.Right); | |
// result | |
return leftIsEquals && rightIsEquals; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment