fork download
  1. /**
  2.  * Node Class of Tree
  3.  * @author Prateek
  4.  */
  5. class Node {
  6. public Node left;
  7. public int data;
  8. public Node right;
  9.  
  10. public Node(int val) {
  11. this.data=val;
  12. }
  13.  
  14. @Override
  15. public String toString(){
  16. return this.data + "";
  17. }
  18. }
  19.  
  20. /**
  21.  * Check if Binary Tree is Symmetric
  22.  * @author Prateek
  23.  */
  24. class SymmetricBinaryTree {
  25. /**
  26. * Sub-routine to check if Binary Tree is Symmetric
  27. */
  28. public boolean isSymmetric(Node left, Node right){
  29. if ( (left==null && right!=null) || (left!=null && right==null) )
  30. return false;
  31.  
  32. if(left==null && right==null)
  33. return true;
  34.  
  35. return isSymmetric(left.left,right.right) && isSymmetric(left.right,right.left);
  36. }
  37.  
  38. public static void main(String[] args) {
  39. SymmetricBinaryTree obj = new SymmetricBinaryTree();
  40.  
  41. Node root = new Node(1);
  42.  
  43. root.left = new Node(2);
  44. root.left.left = new Node(4);
  45. root.left.right = new Node(5);
  46.  
  47. root.right = new Node(3);
  48. root.right.left = new Node(6);
  49. root.right.right = new Node(7);
  50.  
  51. boolean isSymmetric = obj.isSymmetric(root.left,root.right);
  52. System.out.println(isSymmetric);
  53. }
  54. }
  55.  
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
true