Guest User

Untitled

a guest
Nov 18th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. private static bool CompareIterative(BTN n1, BTN n2)
  2. {
  3. // check for nulls
  4. if (n1 == null || n2 == null)
  5. {
  6. return n1 == n2;
  7. }
  8.  
  9. var q1 = new Queue<BTN>();
  10. var q2 = new Queue<BTN>();
  11.  
  12. q1.Enqueue(n1);
  13. q2.Enqueue(n2);
  14.  
  15. while (q1.Count > 0 && q2.Count > 0)
  16. {
  17. // get nodes and compare them
  18. var tempNode1 = q1.Dequeue();
  19. var tempNode2 = q2.Dequeue();
  20.  
  21. if (tempNode1.Val != tempNode2.Val)
  22. {
  23. return false;
  24. }
  25.  
  26. // enqueue Left children of both nodes
  27. if (tempNode1.Left != null && tempNode2.Left != null)
  28. {
  29. q1.Enqueue(tempNode1.Left);
  30. q2.Enqueue(tempNode2.Left);
  31. }
  32. else if (tempNode1.Left == null && tempNode2.Left == null)
  33. {
  34. // do nothing
  35. }
  36. else if (tempNode1.Left == null || tempNode2.Left == null)
  37. {
  38. return false;
  39. }
  40.  
  41. // enqueue Right children of both nodes
  42. if (tempNode1.Right != null && tempNode2.Right != null)
  43. {
  44. q1.Enqueue(tempNode1.Right);
  45. q2.Enqueue(tempNode2.Right);
  46. }
  47. else if (tempNode1.Left == null && tempNode2.Left == null)
  48. {
  49. // do nothing
  50. }
  51. else if (tempNode1.Right == null || tempNode2.Right == null)
  52. {
  53. return false;
  54. }
  55. }
  56.  
  57. return true;
  58. }
  59.  
  60. private static bool CompareRecursive(BTN n1, BTN n2)
  61. {
  62. // check for nulls
  63. if (n1 == null || n2 == null)
  64. {
  65. return n1 == n2;
  66. }
  67.  
  68. // check data of the root nodes
  69. if (n1.Val != n2.Val)
  70. {
  71. return false;
  72. }
  73.  
  74. // check left sub trees recursively
  75. var leftIsEquals = CompareRecursive(n1.Left, n2.Left);
  76.  
  77. // check right sub trees recursively
  78. var rightIsEquals = CompareRecursive(n1.Right, n2.Right);
  79.  
  80.  
  81. // result
  82. return leftIsEquals && rightIsEquals;
  83. }
Add Comment
Please, Sign In to add comment