Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
Add Comment
Please, Sign In to add comment