Advertisement
unknown_0711

Untitled

Oct 23rd, 2022
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class node
  6. {
  7. int data;
  8. node left;
  9. node right;
  10. node(int d)
  11. {
  12. data=d;
  13. left=right=null;
  14. }
  15. }
  16. public class Main
  17. {
  18. node root=null;
  19. //insert function
  20. void insertFunction(int value)
  21. {
  22. root=insert(root,value);
  23. }
  24. node insert(node currentNode,int value)
  25. {
  26. if(currentNode==null)
  27. {
  28. currentNode=new node(value);
  29. return currentNode;
  30. }
  31. if(value<currentNode.data)
  32. {
  33. currentNode.left=insert(currentNode.left,value);
  34. }
  35. else
  36. {
  37. currentNode.right=insert(currentNode.right,value);
  38. }
  39. return currentNode;
  40.  
  41. }
  42. static boolean isSameTree(Main obj1,Main obj2)
  43. {
  44. return isSameTreeFunc(obj1.root,obj2.root);
  45. }
  46. static boolean isSameTreeFunc(node p,node q)
  47. {
  48. if(p==null&& q==null)
  49. {
  50. return true;
  51. }
  52. if(p==null||q==null)
  53. return false;
  54. if(p.data==q.data && isSameTreeFunc(p.left,q.left)
  55. && isSameTreeFunc(p.right,q.right))
  56. // {
  57. return true;
  58. //}
  59. return false;
  60. }
  61. public static void main (String[] args) throws java.lang.Exception
  62. {
  63. //your code here
  64. Scanner sc=new Scanner(System.in);
  65. int n1=sc.nextInt();
  66.  
  67. Main ob1=new Main();
  68.  
  69. int n2=sc.nextInt();
  70. Main ob2=new Main();
  71. for(int i=0;i<n1;i++)
  72. {
  73. ob1.insertFunction(sc.nextInt());
  74. }
  75. for(int i=0;i<n2;i++)
  76. {
  77. ob2.insertFunction(sc.nextInt());
  78. }
  79. boolean ans=isSameTree(ob1,ob2);
  80. if(ans)
  81. {
  82. System.out.println("YES");
  83. }
  84. else
  85. {
  86. System.out.println("NO");
  87. }
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement