Guest User

Untitled

a guest
Oct 20th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. //A simple and efficient program that check's if a binary tree is symmetrical (i.e) if one side is the mirror reflection of another .
  2.  
  3. class Tree {
  4. public boolean checkSymmetric(TreeNode root) {
  5. //An helper function that keeps track of my left and right subtrees.
  6. return help( root, root);
  7. }
  8.  
  9. public static boolean help(TreeNode left,TreeNode right)
  10. {
  11. //Base case when we reach end of tree
  12. if(left == right && left == null)
  13. return true;
  14. else if(left == null || right == null)
  15. return false;
  16.  
  17. // Check for non symmetry at every point
  18. if(left.val != right.val)
  19. return false;
  20. // Keep check the reflection of the left and right tree at the same time
  21. return help(left.left,right.right) &&
  22. help(left.right,right.left);
  23.  
  24. }
  25. }
Add Comment
Please, Sign In to add comment